根据 MSDN(Integer Types - VC2008):
The type for a decimal constant without a suffix is either int, long int, or unsigned long int. The first of these three types in which the constant's value can be represented is the type assigned to the constant.
在 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
最佳答案
-2147483648
不是整数文字。它是应用于整数文字 2147483648
的一元运算符 -
。该文字的值不适合 signed int
或 signed long
,因此它的类型为 unsigned long
。 -
运算符不会更改该类型。
关于C++整数常量的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29211701/