No Name QA
No Name QA

Reputation: 784

What integer type does bitwise shift use as shift size?

I'm trying to find information about shift's size type in C++. For example:

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

So what type does C++ use for the shift size?

Upvotes: 2

Views: 197

Answers (3)

rhaport
rhaport

Reputation: 550

The standard §8.5.7 says:

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.

So, to me the right operand should be promoted. That means it will be promoted to int, unsigned int, long etc. You can read the whole paragraph with different rules depending on the type of your variable

Upvotes: 0

M.M
M.M

Reputation: 141534

It is explained in [expr.shift]/1: (N4860)

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

Unlike most other binary operators, the usual arithmetic conversions are not performed. The integral promotions mean that in your examples the operands of type char and short are promoted to int (on normal systems) and the others are unchanged.

Upvotes: 4

Laurent Jospin
Laurent Jospin

Reputation: 614

It can be any type: https://en.cppreference.com/w/cpp/language/operator_arithmetic

In fact the compiler will decide how to cast, and might use intermediate type as it whish. What is garanteed is that if both a and b are positive, the result of a << b is well defined and has the same type as a.

If a or b is negative, the result is undefined and implementation dependent.

Upvotes: 0

Related Questions