Joy
Joy

Reputation: 41

C Programming on storage of bits in byte

#include<stdio.h>

int main()
{
    char a = 128;
    char b = -128;
    printf("a is %d -- b is %d \n",a,b);

    return 0;
}

The output is :

a is -128 -- b is -128

As the signed character range is from 0 to 127, from the above code can you please explain how the value is assigned for the out of boundary values.

Thanks in Advance.

Upvotes: 0

Views: 368

Answers (1)

dreamlax
dreamlax

Reputation: 95315

The range of a char type depends on the implementation. If it is a signed type, then its range is at least from -128 to 127, and if it is an unsigned type its range is at least from 0 to 255 (these are the ranges that the type must support at a bare minimum, the range supported by the type may actually be larger than this depending on the implementation).

Also note, that when you assign an integer to a signed type that cannot hold that value, you are invoking undefined behaviour. So assigning 128 to a signed char that cannot hold 128 (e.g. when 128 is greater than CHAR_MAX) is invoking undefined behaviour. In this case, it has wrapped around to -128 because it shares the same byte representation as an unsigned char type holding 128, but as with all instances of undefined behaviour, you cannot guarantee that this will be the case on all implementations.

Upvotes: 4

Related Questions