When the value is `int` at max and checked with postfix ++, is the code correct?

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 
+7
c language-lawyer
source share
2 answers

Regardless of area i , the program has undefined behavior in evaluating i++ when i is 2147483647 (assuming INT_MAX = 2147483647 on your system).

Your example can be rewritten as:

 include <limits.h> int main(void) { // Specified behavior when `i` has the value `INT_MAX`? { int i = INT_MAX; i++; } puts("Done"); return 0; } 

The calculation of the i++ value leads to an integer overflow regardless of whether the calculated value is used or if this object ceases to exist immediately after the next point in the sequence; the point of the sequence or the duration of the storage of the object does not matter if undefined behavior exists here.

+4
source share

The code has undefined behavior. The expression i++ causes the score i+1 and assignment of the result i , and the score i+1 has undefined behavior. It does not matter that you are not using the result i+1 or the newly saved value i . UB is not a matter of using the result. Similarly, 0*(INT_MAX+1) has UB.

+4
source share

All Articles