gpt4 book ai didi

c++ - 为什么十进制和十六进制整数文字的处理方式不同?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:28:30 24 4
gpt4 key购买 nike

阅读 Stanley Lippman 的“C++ Primer”,我了解到默认情况下十进制整数文字是带符号的(最小类型的 intlonglong long 其中文字的值适合)而八进制和十六进制文字可以是有符号或无符号的(最小类型的 intunsigned intlong, unsigned long, long longunsigned long long 其中文字的值适合)。

区别对待这些文字的原因是什么?

编辑:我正在尝试提供一些上下文

int main()
{
auto dec = 4294967295;
auto hex = 0xFFFFFFFF;
return 0;
}

在 Visual Studio 中调试以下代码显示 dec 的类型是 unsigned longhex 的类型是 unsigned整数.
这与我读过的内容相矛盾,但仍然:两个变量代表相同的值,但类型不同。这让我很困惑。

最佳答案

C++.2011 更改了 C++.2003 的升级规则。此更改记录在 §C.2.1 [diff.cpp03.lex] 中:

2.14.2
Change: Type of integer literals
Rationale: C99 compatibility

C 标准(C.1999 和 C.2011)在 §6.4.4.1 中定义了转换。 (C++.2011 §2.14.2 本质上是从 C 标准中复制内容。)

The type of an integer constant is the first of the corresponding list in which its value can be represented.

enter image description here
larger image

C.1999 基本原理给出如下解释:

The C90 rule that the default type of a decimal integer constant is either int, long, or unsigned long, depending on which type is large enough to hold the value without overflow, simplifies the use of constants. The choices in C99 are int, long and long long. C89 added the suffixes U and u to specify unsigned numbers. C99 adds LL to specify long long.

Unlike decimal constants, octal and hexadecimal constants too large to be ints are typed as unsigned int if within range of that type, since it is more likely that they represent bit patterns or masks, which are generally best treated as unsigned, rather than “real” numbers.

关于c++ - 为什么十进制和十六进制整数文字的处理方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36560143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com