按位移位使用什么整数类型作为移位大小?

What integer type does bitwise shift use as shift size?

我正在尝试查找有关 C++ 中 shift 大小类型的信息。例如:

int x = 1;

char char_var = 1;
short short_var = 1;
int int_var = 1;
long long_var = 1;
long long long_long_var = 1;

x = x << char_var;  // works
x = x << short_var; // works
x = x << int_var;   // works
x = x << long_var;   // works
x = x << long_long_var;   // works

那么 C++ 使用什么类型的移位大小?

可以是任何类型:https://en.cppreference.com/w/cpp/language/operator_arithmetic

事实上,编译器将决定如何转换,并且可能会根据需要使用中间类型。保证的是,如果 a 和 b 都是正数,则 a << b 的结果定义明确并且与 a 具有相同的类型。

如果 a 或 b 为负,则结果未定义且依赖于实现。

在[expr.shift]/1中有说明:(N4860)

The operands shall be of integral or unscoped enumeration type and integral promotions are performed

与大多数其他二元运算符不同,通常的算术转换 不会执行。 integral promotions 意味着在您的示例中,类型 charshort 的操作数被提升为 int (在正常系统上),其他操作数保持不变。

标准 §8.5.7 说:

The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

所以,对我来说应该提升正确的操作数。这意味着它将被提升为 int、unsigned int、long 等。您可以根据变量的类型使用不同的规则阅读整个段落