Archive for 七月, 2009

类型转换-无处不在的陷阱

4 Comments »

今天在论坛上看有laphon同学的一个问题,觉得这个问题很有意思。
原帖地址
问题援引如下:

做一个小程序的时候发现的。代码如下,使用的编译器为DEV-C++ 4.9.9.2。
如果先要求输入a,再要求输入b,那么a的值无论输入多少(少于255)输出都会是0;
反过来,如果先要求输入b,再要求输入a,那么就会正常。
这是为什么呢?请教达人解释。

#include
#include
 
int main(int argc,char **argv)
{
    unsigned char a,b;
    scanf("%d",&a);
    scanf("%d",&b);
    printf("a=%d,b=%d\n",a,b);
    scanf("%d",&b);
    scanf("%d",&a);
    printf("a=%d,b=%d\n",a,b);
    system("pause");
}

Read the rest of this entry »