- 论坛徽章:
- 0
|
回复 1# zhangyong307189
这个问题没什么意思,和你运行的平台有关系,在一些平台能打印出“80”来,在An Introduction to GCC - for the GNU compilers gcc and g++ 中有一段说明了,“ Most systems, including x86 GNU/Linux and Microsoft Windows, use signed char, but those based on PowerPC and ARM processors typically use unsigned char.(29) This can lead to unexpected results when porting programs between platforms which have different defaults for the type of char. “ 并且在C标准中也没有定义char是 unsigned char或者是 signed char,
不过在x86 gcc上默认的是 signed char(-128--127).
不过本题赋值128会造成溢出,gcc会用一个int型来存储成为-128.而-128在内存中存储的是它的补码形式,128 源码0000,0000, 0000,0000, 0000,0000 ,1000,0000
反码 1111,1111, 1111,1111 ,1111,1111, 0111,1111 加1 成为 1111,1111, 1111,1111, 1111,1111, 1000,0000 (补码) 也就是16进制的 FFFF FF80.
如果用的是GCC 在编译时加上 -funsigned-char 那结果就是80了.- yang23@yang23-laptop:~/tmp$ gcc tmp.c -funsigned-char
- yang23@yang23-laptop:~/tmp$ ./a.out
- 80
- yang23@yang23-laptop:~/tmp$ gcc tmp.c -fsigned-char
- yang23@yang23-laptop:~/tmp$ ./a.out
- ffffff80
- yang23@yang23-laptop:~/tmp$
复制代码 |
|