Finding the maximum char value in C

I find the maximum value of a by charsimple addition and testing when the number is 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 loop test whileruns forward, so the first time a c+1negative one is interrupted, and we print the value c. However, programming outputs a negative number!

Why does this program not output 127?

+4
source share
2 answers

The conditional conditional expression contains an implicit listing, which makes the comparison work with ints, not with characters.

If you change it to

while((char)(c + 1) > 0)
    ++c;

then he will print 127.

+4
source

- undefined. , C c + 1 > 0 true, " " .

, .

0

Source: https://habr.com/ru/post/1649077/


All Articles