Dave Nguyen Dave Nguyen - 2 months ago 21
C Question

Increment of character in C

#include <stdio.h>
#include <stdlib.h>

int main()
{
int count=0;
char c=127;

do
count++;
while(c++);
printf("count=%d ",count);
return 0;
}


Can anybody explain to me why after the first loop, the value of c will become to -128?

Answer

Because your compiler defaults char to signed char. So the range of values for it is -128 to 127, and incrementing 127 is triggering wraparound. If you want to avoid this, be explicit, and declare your variable as unsigned char.

Mind you, to do this correctly, you also want to change the printf; you're printing as a signed int value (%d); to be 100% type correct, you'd want to match types, so the format code should be %hhd for a signed char, or %hhu for an unsigned char. %d will work due to promotion rules with varargs, but it's a bad habit to just use %d all the time; when you print an unsigned with %d, your system will likely succeed, but it will show large values as being negative, confusing you.

Comments