Created
March 31, 2017 08:16
-
-
Save wolf99/42c612bbd00b85b44c468a5b12165689 to your computer and use it in GitHub Desktop.
MISRA classify_number()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
kind classify_number(int n) | |
{ | |
kind class = error; | |
if (n > 0) { | |
int buf = aliquot_sum(n); | |
if (buf > n) { | |
class = abundant_number; | |
} else if (buf < n) { | |
class = deficient_number; | |
} else { | |
class = perfect_number; | |
} | |
} | |
return class; | |
} |
TY @deathsec.
Bear in mind that in a general case this would change if for some reason we were using a float
or a double
because they can have NaN
values, which means the if
is not complete. In that case, to code defensively I might do:
kind classify_number(float n)
{
kind class = error;
if (n > 0) { // This still protects against incorrect parameter
float buf = foo(n); // But this could return NaN
if (buf > n) {
class = abundant_number;
} else if (buf < n) {
class = deficient_number;
} else if (buf == 0) { // Zero is explicitly tested for, as it is a non-error value
class = perfect_number;
} else { // The if still has a finishing else after all the else-if
class = error; // And the else catches the error case (NaN value in this case)
}
}
return class; // Still only one exit point
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
oh this looks good 👍