...
An example of undefined behavior in C99 is the behavior on signed integer overflow. (See also rule INT32-C. Ensure that operations on signed integers do not result in overflow.) This noncompliant code example depends on this behavior to catch the overflow.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <assert.h> int foo(int a) { assert(a + 100 > a); printf("%d %d\n", a + 100, a); return a; } int main(void) { foo(100); foo(INT_MAX); } |
...
This compliant solution does not depend on undefined behavior.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <assert.h> int foo(int a) { assert(a < (INT_MAX - 100)); printf("%d %d\n", a + 100, a); return a; } int main(void) { foo(100); foo(INT_MAX); } |
...