Dave Nguyen
Dave Nguyen

Reputation: 139

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?

Upvotes: 2

Views: 15394

Answers (3)

A.A Noman
A.A Noman

Reputation: 5270

Another easy explanation of this problem

This situation is known as overflow of signed char. Range of unsigned char is -128 to 127. If we will assign a value greater than 127 then value of variable will be changed to a value if we will move clockwise direction as shown in the figure according to number. If we will assign a number which is less than -128 then we have to move in anti-clockwise direction.

When variable value is 127 then it's ok. But if variable value increment by 1 then clock wise increment also 1 and it's position value -128. So your output is -128.

Demo Image

Demo Link

Upvotes: 2

CS_EE
CS_EE

Reputation: 449

try using unsigned char to count up to 255

Upvotes: 1

ShadowRanger
ShadowRanger

Reputation: 155477

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.

Upvotes: 8

Related Questions