Reputation: 7223
I am finding the maximum value of a char
by simple addition and testing for when the number goes negative:
#include<stdio.h>
/*find max value of char by adding*/
int main(){
char c = 1;
while(c + 1 > 0)
++c;
printf("Max c = %d\n",(int)c); /*outputs Max c = -128*/
return 0;
}
The while
loop tests ahead, so the first time c+1
is negative it breaks and we print the value of c
. However, the programming is outputting the negative number!
Why doesn't this program output 127
?
Upvotes: 5
Views: 7770
Reputation: 7802
Signed integer overflow is undefined behavior. This means that a conforming C compiler is allowed to change c + 1 > 0
to true
, because the addition "cannot" overflow.
This means that your program could legitimately be compiled to an endless loop.
Upvotes: 1
Reputation: 35324
There is an implicit cast occurring in the while conditional which is causing the comparison to work on ints rather than chars.
If you change it to
while((char)(c + 1) > 0)
++c;
then it will print 127.
Upvotes: 5