Liste des Groupes | Revenir à cl c |
On 05/11/2024 13:42, Waldek Hebisch wrote:
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.Your example is an improvement on your previous ones. At least it attempts to deal with out-of-range conditions!
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.
// Take a pointer to an array of two ints, add them, and return the sumThis is a different category of error.
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?).
Les messages affichés proviennent d'usenet.