CppCon 2018: JF Bastien “Signed integers are two's complement”
Why Stack Overflow recommends it
Stack Overflow users link it as the authoritative background for C++20's two's complement requirement and for why signed overflow nonetheless stays undefined behavior.
Recommended by 1 people across 1 different months, 2022 to 2024.
What it is
A CppCon 2018 talk by JF Bastien, an Apple compiler engineer who leads C++ development there, on why signed integers in C++ should be defined as two's complement. It tours the old world of ones' complement, signed magnitude, padding bits and undefined behavior that the C++20 change removed.
What people said
Recommends Adrian McCarthy · 2024-10 · Stack Overflow · on “Why is Signed Overflow due to computation still Undefined Behavior in C++20”
Based on JF Bastien's 2018 CppCon talk [this video] : Many (most?) integer overflows are bugs—not just because they open the door to undefined behavior, but also because, even if the overflow was defined to wrap, the code would still be wrong. Your compiler and other tools could help you find these bugs by trapping on overflow, which is allowed because overflow is UB, so the compiler can do whatever it wants. If the behavior were defined, the compiler wouldn't have the flexibility to help. Thus the standard declares that the representation shall be two's complement. It does not require define how the arithmetic operations should behave when there's an overflow because there is no good solution th
Cites Qaz · 2022-01 · Stack Overflow · on “Is (int)(unsigned)-1 == -1 undefined behavior”
@JasonLiam, While this changed with the paper that required two's complement, the answer cites why it was implementation-defined regardless of two's complement. If `int` and `unsigned` have an equal number of bits, then no matter what representation is used, the value `UINT_MAX` (required from `(unsigned)-1`, it's not a `reinterpret_cast`) is never going to fit into an `int`, so the conversion was always implementation-defined. The paper also proposed wrap-around overflow, but went back on that: [this video]
Cites tbxfreeware · 2023-08 · Stack Overflow · on “why not work for 5 to 7 input ? Decimal to Binary conversion in c++”
This is similar to what I had in my toolbox for a long time. It avoids what could be an "expensive" multiply operation, especially when floating point values are involved. When `n` is negative, your code exposes what is presumably a two's-complement implementation for signed integers. In real life, every computer uses two's-complement [this video] , but the C++ Standard still maintains the fiction that some might not, and calls it an implementation detail. On that basis, your code is _nominally_ not portable. In real life, however, it is.