Search code examples
ccharmaxlimitansi-c

Finding max value of char in C


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?


Solution

  • 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.