C++整数常量的类型

标签 c++ types long-integer

根据 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 intsigned long,因此它的类型为 unsigned long- 运算符不会更改该类型。

关于C++整数常量的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29211701/

相关文章:

c++ - C Header 定义顺序/位置

generics - 复制 Kotlin 数组减去特定索引处的元素

python - 在 python 中检查变量是否为数字类型的最佳方法是什么

python - Long Int 文字 - 语法无效?

java - 为什么在 x64 Java 中 long 比 int 慢?

c++ - 如果一个对象在本地创建并在 C++ 中作为异常抛出,那么本地对象如何在其范围之外有效,即在 catch block 中?

c++ - http ://tinyurl. com/pzpyvb9 处的无锁堆栈的性能数据是否真实?

c - C 中长数计算的错误答案

c++ - 对递归数独回溯函数的模糊调用。

typescript - 无法从类字典扩展类