The C Standard, section Section 3.4.3 [ISO/IEC 9899:2011], defines undefined behavior as
...
An example of undefined behavior in C is the behavior on signed integer overflow. (See also 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); } |
...