【发布时间】:2015-05-26 12:41:23
【问题描述】:
根据 MSDN (Integer Types - VC2008):
不带后缀的十进制常量的类型是 int、long int 或 unsigned long int。这三种类型中的第一种 常量的值可以表示为分配给 常数。
在Visual C++ 2008上运行以下代码:
void verify_type(int a){printf("int [%i/%#x]\n", a, a);}
void verify_type(unsigned int a){printf("uint [%u/%#x]\n", a, a);}
void verify_type(long a){printf("long [%li/%#lx]\n", a, a);}
void verify_type(unsigned long a){printf("ulong [%lu/%#lx]\n", a, a);}
void verify_type(long long a){printf("long long [%lli/%#llx]\n", a, a);}
void verify_type(unsigned long long a){printf("unsigned long long [%llu/%#llx]\n", a, a);}
int _tmain(int argc, _TCHAR* argv[])
{
printf("sizeof(int) %i\n", sizeof(int));
printf("sizeof(long) %i\n", sizeof(long));
printf("sizeof(long long) %i\n\n", sizeof(long long));
verify_type(-2147483647);
verify_type(-2147483648);
getchar();
return 0;
}
我明白了:
sizeof(int) 4
sizeof(long) 4
sizeof(long long) 8
int [-2147483647/0x80000001]
ulong [2147483648/0x80000000] <------ Why ulong?
我希望 const -2147483648 () 是 int。为什么我得到的是 ulong,而不是 int?
我已经编程了很长时间,直到今天我还没有注意到 + 或 - 不是整数常量的一部分。这一提示说明了一切。
integer-constant:
decimal-constant integer-suffix<opt>
octal-constant integer-suffix<opt>
hexadecimal-constant integer-suffix<opt>
decimal-constant:
nonzero-digit
decimal-constant digit
octal-constant:
0
octal-constant octal-digit
hexadecimal-constant:
0x hexadecimal-digit
0X hexadecimal-digit
hexadecimal-constant hexadecimal-digit
nonzero-digit: one of
1 2 3 4 5 6 7 8 9
octal-digit: one of
0 1 2 3 4 5 6 7
hexadecimal-digit: one of
0 1 2 3 4 5 6 7 8 9
a b c d e f
A B C D E F
integer-suffix:
unsigned-suffix long-suffix<opt>
long-suffix unsigned-suffix<opt>
unsigned-suffix: one of
u U
long-suffix: one of
l L
【问题讨论】:
-
这个让我很烦。我在这里也有不同的结果:ideone.com/HyyI3r
-
请注意,您的许多
printf语句会导致未定义的行为。您不能将负值传递给%x或%lx。 -
C 中没有函数重载,所以代码在 C 中无法编译。这是一些 C++ 的东西。
-
@Orace 您正在使用 C++11 来获得这些结果,但是 OP 使用的是 2008 编译器。在 C++11 之前,C++ 没有
long long,因此必须使用编译器扩展。编译器扩展应该被记录在案...... -
当表示为 32 位时,值 2147483648 和 -2147483648 具有完全相同的值:
0b10000000000000000000000000000000。编译器如何知道使用哪个?
标签: c++ types long-integer