Skip to content

Instantly share code, notes, and snippets.

@wolf99
Created March 31, 2017 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolf99/42c612bbd00b85b44c468a5b12165689 to your computer and use it in GitHub Desktop.
Save wolf99/42c612bbd00b85b44c468a5b12165689 to your computer and use it in GitHub Desktop.
MISRA classify_number()
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;
}
Copy link

ghost commented Mar 31, 2017

oh this looks good 👍

@wolf99
Copy link
Author

wolf99 commented Mar 31, 2017

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