Reputation:
I have just started my Data types revised chapter. I am currently studying the concept of signed and unsigned character. My doubt is that the signed char has a range from -128 to 127, then why the below code is still running ? Also, the below code is giving the infinite o/p which is not understandable to me.
main( )
{
char ch ;
for ( ch = 0 ; ch <= 255 ; ch++ )
printf ( "\n%d %c", ch, ch ) ;
}
I am currently using GCC 32-bit compiler. Can anyone please help me in explaining the o/p of the above code ?
Upvotes: 0
Views: 234
Reputation: 14367
You are probably confused with the output. I think in the o/p you are seeing something like this.
0
1
2
3 ...
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32...
33 ! 34 " .... 125 } 126 ~ 127
255 � 256 257
... 511 � 512 513 .. and so on
0 to 32 are all flags(unprintable codes)
(hence you dont see the output , but only the numbers for the first 33), followed by characters till 127
. As you can see it wraps around at every 255 characters to give you the same result but it actually stops printing characters after multiples of 127
( this is the 127 char list - http://web.cs.mun.ca/~michael/c/ascii-table.html) . It just resets after 127 to -128, so the program continues to print numbers to infinity even though it is resetting the char.
This is because when you do printf("%d",ch) for -127 it prints 128
, and so on until ch = 255 and then it flips again and starts printing 256 onwards and so on but the actual ch value never goes above 127 and hence it goes to infinity
A signed char c
should you be giving you the above output. A char is essentially an integer 8 bits wide, but by default probably signed on your compiler.
Upvotes: 0
Reputation: 121
Because signed character is from -128 to 127, its binary number are 10000000 and 01111111, When 'ch' run to 127, next increment 'ch' will become -128, always less than 255, so it will infinite o/p.
Upvotes: 1
Reputation: 48330
for ( ch = 0 ; ch <= 255 ; ch++ )
If ch
is a signed character, it will start at 0 and increment to 127. Then, at the next increment, it will "wrap around" and become -128. Using an unsigned char
:
127 = 0x7F
128 = 0x80
But, using a signed char, 0x80
becomes -128.
So now ch
will run from -128 through 127. And since all of those values are less than 255, this will repeat until you stop the program..
Upvotes: 4