...
In this example, the programmer has mistakenly omitted the comparison operator (see MSC02-A. Avoid errors of omission) from the conditional statement, which should be getchar() != EOF
. After macro expansion, the conditional expression is incorrectly evaluated as a binary operation: getchar()-1
. This is syntactically correct, even though it is certainly not what the programmer intended. Note that this example also violates DCL00-A. Declare immutable objects as constantsnamed constant values.
Parenthesizing the -1
in the declaration of EOF
ensures that the macro expansion is evaluated correctly.
...
In this compliant solution, we replace the macro definition with an enumeration constant in compliance with DCL00-A. Declare immutable objects as constantsnamed constant values.
Code Block | ||
---|---|---|
| ||
enum { EOF = -1 }; /* ... */ if (getchar() != EOF) { /* ... */ } |
...