Displaying the ASCII characters in C without unsigned char

331 views Asked by At
unsigned char a;

for(a=32;a<128;a=a+1)
printf("%d='%c'\t",a,a);
return(0);

Why do I have to put unsigned char? When I left it as char, I executed the program and it was giving me an infinite loop. Shouldn't it stop when a=127?

3

There are 3 answers

6
mastov On

On Visual Studio, the type char is the same as signed char and has a range of -128 to +127 (both included), so all values of signed char are below 128. Therefore the loop condition a < 128 is always fulfilled and the loop never stops.

When you have unsigned char, the value of a reaches 128 at some point and there won't be a next iteration. In change, if you try to increase a signed char variable of value 127 (expecting it to take the value 128), the result is undefined. On most platforms (including Visual Studio) it will wrap around (overflow because 127 is the highest possible value) to the lowest possible value -128.

8
haccks On

char means either it is signed or unsigned depends on implementation. This makes the behaviour of your code implementation defined.
It seems that on your machine it is signed. The minimum and maximum value of signed char is -127 & +127 respectively as per C standard. Any value greater that 127 or less than -127 can't be assigned to a otherwise it will invoke undefined behaviour.

After a reaches 127, it is incremented by one and the value becomes 128 which can't be hold by a signed char variable and hence the code invokes undefined behaviour.

0
too honest for this site On

Whether char is signed or unsigned is implementation dependent and may change by compiler and target architecture.

For most (likely all modern) CPU architectures, signed char has a range of -128...127, unsigned char has 0...255 (see your limits.h, the minimum range is -127...127, no upper limit).

So, char appears to be signed for your example. As compares are done using int here (type coercion - implicit conversion), the condition of your loop will always be true, thus the loop never terminates.

Using unsigned benefits from the extended range, so the loop operates normally.

Note that if doing arithmetic on char, always use explicitly signed or unsigned. The latter is often the better choice. If you enable warnings, the compiler might help you with that. However, do not rely on this (but follow the warnings showing up).