Given the following in C++(you might be surprised):
unsigned short x=0xFFFF;
unsigned short y=0xFFFF;
auto z=x*y;
std::cout << z;
Without checking, assuming an LP64 system what is the result:
A. 4294836225
B. -131071
C. fffe0001
D. Undefined behavior
#Cplusplus
#Cpppolls
-
-
This is an unfortunate result of the Usual Arithmetic Conversions: https://en.cppreference.com/w/c/language/conversion#Usual_arithmetic_conversions … Before performing binary operations we need to bring the operands to a common type via the Usual Arithmetic Conversions. See [expr.mul]p2 http://eel.is/c++draft/expr.mul#2 …pic.twitter.com/oWGx6V6fol
Prikaži ovu nit -
and [expr.arith.conv] http://eel.is/c++draft/expr.arith.conv … Then we hit the integral promotions [expr.arith.conv]p1.5 http://eel.is/c++draft/expr.arith.conv#1.5 … and then [conv.prom]p1 http://eel.is/c++draft/conv.prom#1 …pic.twitter.com/wPrKNB5gyE
Prikaži ovu nit -
We also need [conv.rank]p1.3 http://eel.is/c++draft/conv.rank#1.3 … to tell us that the rank of short int is < int Which finally tells us that both operands will be converted to int and we end up with signed integer overflow which is undefined behavior, see [expr.pre]p4 http://eel.is/c++draft/expr#pre-4 …pic.twitter.com/DoIPqHEwP5
Prikaži ovu nit -
Alternatively casting one of the operands to a larger unsigned type would have results in both operands becoming unsigned e.g. auto z = static_cast<unsigned>(x)*y; Also see the following godbolt: https://godbolt.org/z/LyfLi- pic.twitter.com/P352YITBQ2
Prikaži ovu nit -
We could have caught this using a couple of methods. First if we were using UBSan this would have generated a runtime failure:https://godbolt.org/z/d2CBrk
Prikaži ovu nit -
If we used constexpr in a context that required a constant expression this would have generated a compile-time diagnostic: https://godbolt.org/z/WCi4BA Also see “Exploring undefined behavior via constexpr”:https://twitter.com/shafikyaghmour/status/1127219879457636353 …
Prikaži ovu nit -
Also see “Why must a short be converted to an int before arithmetic operations in C and C++” https://stackoverflow.com/a/24372323/1708801 …pic.twitter.com/hfcr9IBcN1
Prikaži ovu nit
Kraj razgovora
Novi razgovor -
-
-
Hvala. Twitter će to iskoristiti za poboljšanje vaše vremenske crte. PoništiPoništi
-
-
-
Hvala. Twitter će to iskoristiti za poboljšanje vaše vremenske crte. PoništiPoništi
-
-
-
Hvala. Twitter će to iskoristiti za poboljšanje vaše vremenske crte. PoništiPoništi
-
Čini se da učitavanje traje već neko vrijeme.
Twitter je možda preopterećen ili ima kratkotrajnih poteškoća u radu. Pokušajte ponovno ili potražite dodatne informacije u odjeljku Status Twittera.
The answer is D, this is undefined behavior but how you might protest, unsigned number don’t have undefined behavior on overflow, do they?