为什么短裤不应该使用整数文字?
Why shouldn't shorts use integer literals?
根据cppreference,
以下语句在 C++ 中无效:
unsigned short test = 5u;
为什么在未签名的短裤上不允许使用后缀 u
或 U
?
代码仍然可以编译,但是这样做有什么影响吗?
table 偏好 table 6 来自 [lex.icon]
之所以没有讨论 short
是因为整型文字的最小类型是 int
(来自后缀 none 部分)。由于 int
保证与 int
大小相同或更大,因此没有理由调用 short
.
unsigned short test = 5u;
有效,它会隐式地将 5u
转换为 unsigned short
您误读了 cppreference。它说的(不是这些话)是:
- 以 U 结尾的文字是
unsigned int
(或 unsigned long int
或 unsigned long long int
)
请注意,它没有说明任何有关 'invalid' 等的内容
在你的例子中
unsigned short test = 5u;
5u
文字 是 一个 unsigned int
.
变量 test
是 而不是 和 unsigned int
。这是一个unsigned short
。编译器插入一个隐式转换,这是完全合法的。
5u
不是 unsigned short
类型,但这并不意味着 unsigned short test = 5u;
是 "illegal".
发生通常的转换。由于所有 unsigned int
对某些 n
取模 2^n
,这只是截断右侧 "bit wise" 的值。只要 rhs 值适合 short,什么也不会发生;如果没有,则采用 "low order bits"。
我在引号中谈到 "bits",因为它实际上是标准下 n
的某些值的数学模 2^n
。这与位相同,但不要求 C++ 环境实际使用明显的布局来实现它。
cppreference 还说:
The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used.
这意味着 5u
是一个 unsigned int
,因为 5 在该类型的范围内。
如果值太大,如9887766554433u
,如果该类型比unsigned int
宽并且可以容纳该值,它将是一个unsigned long
,否则类型将是unsigned long long
.
这很重要,例如,如果您使用 auto
声明您的变量:
const auto x = 9887766554433u;
此处 x
的类型足以容纳该值。
根据cppreference,
以下语句在 C++ 中无效:
unsigned short test = 5u;
为什么在未签名的短裤上不允许使用后缀 u
或 U
?
代码仍然可以编译,但是这样做有什么影响吗?
table 偏好 table 6 来自 [lex.icon]
之所以没有讨论 short
是因为整型文字的最小类型是 int
(来自后缀 none 部分)。由于 int
保证与 int
大小相同或更大,因此没有理由调用 short
.
unsigned short test = 5u;
有效,它会隐式地将 5u
转换为 unsigned short
您误读了 cppreference。它说的(不是这些话)是:
- 以 U 结尾的文字是
unsigned int
(或unsigned long int
或unsigned long long int
)
请注意,它没有说明任何有关 'invalid' 等的内容
在你的例子中
unsigned short test = 5u;
5u
文字 是 一个 unsigned int
.
变量 test
是 而不是 和 unsigned int
。这是一个unsigned short
。编译器插入一个隐式转换,这是完全合法的。
5u
不是 unsigned short
类型,但这并不意味着 unsigned short test = 5u;
是 "illegal".
发生通常的转换。由于所有 unsigned int
对某些 n
取模 2^n
,这只是截断右侧 "bit wise" 的值。只要 rhs 值适合 short,什么也不会发生;如果没有,则采用 "low order bits"。
我在引号中谈到 "bits",因为它实际上是标准下 n
的某些值的数学模 2^n
。这与位相同,但不要求 C++ 环境实际使用明显的布局来实现它。
cppreference 还说:
The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used.
这意味着 5u
是一个 unsigned int
,因为 5 在该类型的范围内。
如果值太大,如9887766554433u
,如果该类型比unsigned int
宽并且可以容纳该值,它将是一个unsigned long
,否则类型将是unsigned long long
.
这很重要,例如,如果您使用 auto
声明您的变量:
const auto x = 9887766554433u;
此处 x
的类型足以容纳该值。