Consider this program
#include <limits.h>
int main (void) {
int i = 0;
// Assume, user is a fair person, following the instruction strictly..
printf ("Enter a number in the range [0 - INT_MAX] : \n");
scanf ("%d", &i);
while (i++ < INT_MAX) {
// do some stuff..
// value of variable i not used in loop body
}
// value of variable i is not used anywhere after loop body
return 0;
}
In the last evaluation of loop condition i++ < INT_MAX
, the value of i
in the expression will be INT_MAX
, but i
will be holding the result of INT_MAX + 1
(side effect of post increment), which is essentially signed integer overflow. The loop condition (INT_MAX < INT_MAX)
result in false
and loop exits. The value of variable i
not used anywhere in the program after the loop body but, of course, once the loop exits it is holding the result of INT_MAX + 1
.
Does this program possess undefined behavior?
PS:
- I have searched around it and found a couple of related question but they are not exactly same:
does-integer-overflow-cause-undefined-behavior-because-of-memory-corruption
is-it-undefined-behavior-if-the-intermediate-result-of-an-expression-overflows
In both the above question, the value of variable/expression resulting in overflow is used in some way or other.
My question is very specific and pointed to undefined behavior, I am not looking for any other way of doing stuff shown in sample program. I know very well, how to avoid UB.
I would appreciate if you include citation (if any), supporting the behavior (whether UB or not), from language standard in your post.