...
Compliant Solution (GCC)
GCC's Statement Expressions along with the s __typeof extension make it possible to declare and assign the value of the macro operand to a temporary of the same type and perform the computation on the temporary, thus guaranteeing that the operand will be evaluated exactly once:
| Code Block | ||||
|---|---|---|---|---|
| ||||
#define ABS(x) do ({ __typeof (x) __tmp = x; __tmp < 0 ? -__tmp : __tmp; } while(0) |
Note that relying on such extensions makes code nonportable and goes against MSC14-C. Do not introduce unnecessary platform dependencies.
This code comes very close to violating DCL37-C. Do not declare or define a reserved identifier. It technically complies with this rule because it falls under exception DCL37-EX1EX0. However, this code is potentially unsafe if it were invoked with a variable named __tmp. Such calling code would constitute a genuine violation of DCL37-C. Finally, this code is unsafe if it is ever invoked on a platform where __tmp actually has special meaning (see DCL37-C for more information). These are considered acceptable problems, as C provides no mechanism to declare a variable in a scope that is guaranteed to be distinct from all other variables in the same scope.
Exceptions
PRE31-EX1EX0: An exception can be made for invoking an unsafe macro with a function call argument provided that the function has no side effects. However, it is easy to forget about obscure side effects that a function might have, especially library functions for which source code is not available; even changing errno is a side effect. Unless the function is user-written and does nothing but perform a computation and return its result without calling any other functions, it is likely that many developers will forget about some side effect. Consequently, although this exception is allowed, it is not recommended.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...