c - When an `int` at max value and tested with with postfix ++, is code well-defined? -
example example of undefined behavior behavior on integer overflow. c11dr §3.4.3 3
int
overflow undefined behavior, apply following exists loop, , not use the side effect of out-of-scope i
? in particular, postfix increment spec help?
... value computation of result sequenced before side effect of updating stored value of operand. ... §6.5.2.4 2
compiles without warnings well-enabled c11
#include <limits.h> #include <stdio.h> int main(void) { // specified behavior when `i` has value `int_max`? (int = int_max - 2; i++ < int_max;) { printf("%d\n", i); } puts("done"); return 0; }
sample output
2147483646 2147483647 done
of course code can re-written avoid quandary below. still, looking confirmation concerning above. (i think ub.) similar issue exists int_min
, i--
.
(int = int_max - 2; < int_max;) { i++; printf("%d\n", i); }
gnu c11 (gcc) version 5.3.0 (i686-pc-cygwin) compiled 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
regardless of scope i
, program has undefined behaviour in evaluaton of i++
when i
2147483647 (assuming int_max=2147483647 on system).
your example can re-written as:
include <limits.h> int main(void) { // specified behavior when `i` has value `int_max`? { int = int_max; i++; } puts("done"); return 0; }
the value computation of i++
results in integer overflow irrespective of whether computed value used or if object cease exist right after next sequence point; sequence point or storage duration of object irrelevant whether there's undefined behaviour here.
Comments
Post a Comment