uint16_t res = a + (b << 8);
C 2018 6.5.7 covers <<
. Paragraph 3 says the integer promotions are performed on both operands. So the uint8_t
b
is promoted to int
. 8
is already an int
, so the integer promotions technically occur but have no effect.
6.5.6 covers binary +
. For arithmetic operands, paragraph 4 says the usual arithmetic conversions are performed on the operands (jointly). When both operands are integers, the usual arithmetic conversions include the integer promotions on both operands, per 6.3.1.8 1. So the uint8_t
a
is promoted to int
. Note that in the semantics of the C standard, this is not sequenced relative to the shift; it can occur, at least conceptually, either before or after the shift. The integer promotions are also performed on the right operand of +
, (b << 8)
. These again have no effect, but they do occur conceptually after the shift.
uint16_t res = b << 8;
Yes, the integer promotions are applied to b
and 8
, as above.
- Does integer promotion takes place in all kinds of expressions (e.g. even if it's just a shift operation)?
No. The integer promotions are not performed on operands that do not have integer type (such as pointers for floating-point types) and are not included in:
- Parentheses.
- Array subscripting.
- Arguments to functions with prototypes, for arguments matching typed parameters (not those matching
...
in the function declaration).
- Prefix and postfix
++
and --
.
- Unary
&
.
size
and _Alignof
.
- Casts.
+
and -
where one operand is a pointer.
&&
and ||
.
- The first operand of
? :
.
- Simple assignment.
- The comma operator.