首页 / 软件开发 / C++ / C/C++中数的转换
C/C++中数的转换2013-11-04问题: d=1,-d==?我们看看答案会是什么样的:-----------------------------下面的代码的 输出是什么?int main() { char dt = "1";long tdt;tdt = -dt; printf("%ld
", tdt);}我的第一反应是这个输出应该是”-1“。 我想你也是这样认为的。然而如果在64位系统上输出是什么 呢?我期望也是”-1“。 我们看看是这样的吗。让我们测试一下。#xlc -q64 a.c - qlanglvl=extended#./a.out4294967295!! 这里的输出是“4294967295” 而不是“-1”,怎么会这 样呢?别急别急,可能是我们漏了什么? 在回答之前上面问题之前,我们看看下面代码段:"char dt = "1"; -dt;"对于这个代码段,我们确认一下dt变量是有符号还是没有符号的?C我们看看C语言标准怎么说的:The implementation shall define char to have the same range, representation, and behavior as either signed char or unsigned char.也就是说标准没有对char类型变量的符号做要求。我们在看看XL 编译器的文档 http://publib.boulder.ibm.com/infocenter/comphelp/v111v131/topic/com.ibm.xlc111.aix.doc/language _ref/ch.html里面说:By default, char behaves like an unsigned char. To change this default, you can use the -qchars option or the #pragma chars directive. See -qchars for more information.看来XL编译器中,char默认是无符号的。我们可以用-qchars来改变这个默认行为。我们来测 试一下:#xlc -q64 a.c -qlanglvl=extended -qchar=signed#./a.out-1太好了,原来如 此。我们好像明白了。