EXAMPLE An example of undefined behavior is the behavior when integers overflow. C11dr Β§3.4.3 3
Overflow
int is undefined behavior, but is it applicable to the next one that exists in the loop and does not use the side effect now outside the scope of i ? In particular, does this tooltip help with Postfix increment?
... The calculation of the result value is sequenced before the side effect updating the stored value of the operand .... Β§6.5.2.4 2
Compiles without warnings with well-included C11
#include <limits.h> #include <stdio.h> int main(void) { // Specified behavior when `i` has the value `INT_MAX`? for (int i = INT_MAX - 2; i++ < INT_MAX;) { printf("%d\n", i); } puts("Done"); return 0; }
Output example
2147483646 2147483647 Done
Of course, the code can be rewritten to avoid this difficulty with the following. However, seeking confirmation of the foregoing. (I think this is UB.) A similar problem exists with INT_MIN and i-- .
for (int i = INT_MAX - 2; i < INT_MAX;) { i++; printf("%d\n", i); }
GNU C11 (GCC) version 5.3.0 (i686-pc-cygwin) compiled by GNU C version 5.3.0, GMP version 6.1.0, MPFR version 3.1.4, MPC version 1.0.3 '-std=c11' '-O0' '-g3' '-Wpedantic' '-Wall' '-Wextra' '-Wconversion' '-c' '-fmessage-length=0' '-v' '-MMD' '-MP' '-MF' xx.o' '-o' 'xx.o' '-mtune=generic' '-march=i686' /usr/lib/gcc/i686-pc-cygwin/5.3.0/cc1.exe -quiet -v -MMD xx.d -MF xx.d -MP -MT xx.o -dD -Dunix -idirafter ... xx.c
c language-lawyer
chux
source share