Retro C++ quiz #57

Given the following in C++:

#include <cstdint>
#include <limits>

int main() {
int64_t s=32;
int64_t x=std::numeric_limits<int32_t>::max();

1 << s; // A
1 + x; // B
}

Without checking, assuming LP64, which invokes undefined behavior:

A. Both
B. None
C. A
D. B

#Cplusplus
#Cpppolls

A
36.4%
B
27.3%
C
31.8%
D
4.5%
Poll ended at .

The answer is C.

Usually we expect the operands of binary operators to undergo the usual arithmetic conversions but this does not happen for shift operators, only integral promotions: [expr.shift]p1 http://eel.is/c++draft/expr.shift#1.sentence-2

The type of the result is the promoted left operand which in this case would be int: [conv.prom] http://eel.is/c++draft/conv.prom

So we have undefined behavior since the right operand is greater than the bit-width of int in this case: [expr.shift]p1 http://eel.is/c++draft/expr.shift#1.sentence-4

For additive operators the usual arithmetic conversions are performed: [expr.add]p1 http://eel.is/c++draft/expr.add#1

The left operand which is an int is converted to int64_t since they are both signed and int64_t has a greater rank: [expr.arith.conv]p1.5.2 http://eel.is/c++draft/expr.arith.conv#1.5.2

There is no overflow and hence no undefined behavior.

[expr.shift]

@shafik I almost voted A but then I realized that A is not A ;)
@malwareminigun @shafik I voted A for that reason. What a trap!

@kamikaze @malwareminigun

I think @zygoloid dinged me for this trap the first time I posted it 😱

@shafik I said the trap was both beautiful and horrible. And I stand by that. :)

https://www.youtube.com/watch?v=vHfNCJyMfKE

Who Wants To Be A Millionaire Funny-First Letter in the English Alphabet.

YouTube
@shafik why is A not A and B not B?