开发者

Why does the output of this program change at 130?

开发者 https://www.devze.com 2022-12-28 13:57 出处:网络
I have the following code and it seems to me that it should always enter the true part of the if statement but, beyond 120, it appears to start executing the else clause. Why is that happening?

I have the following code and it seems to me that it should always enter the true part of the if statement but, beyond 120, it appears to start executing the else clause. Why is that happening?

char x;
for (i=0;i<256;i+=10) {
    x=i;
    if (x==i)
        printf("%d true\n",i);
    else 
        printf("%d false\n",i);
}

The output is:

0 true
10 true
: all numbers from 20 to 100 are true
110 true
120 true
130 false
140 false
: al开发者_运维百科l numbers from 150 to 230 are false
240 false
250 false


It's because you are using a signed char and presumably an integer.

The char is overflowing when it reaches 130 (it becomes 130 - 256) but the integer does not overflow. 130 - 256 != 130.

A simple change fixes it so that the result is always true - just add unsigned on the first line:

unsigned char x;
for (int i=0;i<256;i+=10)
{
    x=i;
    if (x==i)
        printf("%d true\n",i);
    else 
        printf("%d false\n",i);
}


Your compiler probably uses a signed char by default when you use the char keyword. The range of a signed char is usually -128 to 127, whereas the range of an int is far greater. More esoteric hardware beyond the typical desktop PC may use other values.

0

精彩评论

暂无评论...
验证码 换一张
取 消