简体   繁体   中英

Confusion in the output

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 ?

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..

因为带符号的字符是从-128到127,它的二进制数是10000000和01111111,当“ ch”运行到127时,下一个增量“ ch”将变为-128,始终小于255,因此它将是无限的o / p。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM