Sujet : Re: else ladders practice
De : david.brown (at) *nospam* hesbynett.no (David Brown)
Groupes : comp.lang.cDate : 05. Nov 2024, 14:29:21
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vgd6jh$1hmjc$1@dont-email.me>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Thunderbird/102.11.0
On 05/11/2024 13:42, Waldek Hebisch wrote:
Bart <bc@freeuk.com> wrote:
>
Then we disagree on what 'multi-way' select might mean. I think it means
branching, even if notionally, on one-of-N possible code paths.
OK.
I appreciate this is what Bart means by that phrase, but I don't agree with it. I'm not sure if that is covered by "OK" or not!
The whole construct may or may not return a value. If it does, then one
of the N paths must be a default path.
You need to cover all input values. This is possible when there
is reasonably small number of possibilities. For example, switch on
char variable which covers all possible values does not need default
path. Default is needed only when number of possibilities is too
large to explicitely give all of them. And some languages allow
ranges, so that you may be able to cover all values with small
number of ranges.
I think this is all very dependent on what you mean by "all input values".
Supposing I declare this function:
// Return the integer square root of numbers between 0 and 10
int small_int_sqrt(int x);
To me, the range of "all input values" is integers from 0 to 10. I could implement it as :
int small_int_sqrt(int x) {
if (x == 0) return 0;
if (x < 4) return 1;
if (x < 9) return 2;
if (x < 16) return 3;
unreachable();
}
If the user asks for small_int_sqrt(-10) or small_int_sqrt(20), that's /their/ fault and /their/ problem. I said nothing about what would happen in those cases.
But some people seem to feel that "all input values" means every possible value of the input types, and thus that a function like this should return a value even when there is no correct value in and no correct value out.
This is, IMHO, just nonsense and misunderstands the contract between function writers and function users.
Further, I am confident that these people are quite happen to write code like :
// Take a pointer to an array of two ints, add them, and return the sum
int sum_two_ints(const int * p) {
return p[0] + p[1];
}
Perhaps, in a mistaken belief that it makes the code "safe", they will add :
if (!p) return 0;
at the start of the function. But they will not check that "p" actually points to an array of two ints (how could they?), nor will they check for integer overflow (and what would they do if it happened?).
A function should accept all input values - once you have made clear what the acceptable input values can be. A "default" case is just a short-cut for conveniently handling a wide range of valid input values - it is never a tool for handling /invalid/ input values.