4 ms·
It’s the opposite in cpp: unsigned integer overflow is undefined but signed overflow is defined as wrapping
by alpinisme 11mo ago
It’s the opposite in cpp: unsigned integer overflow is undefined but signed overflow is defined as wrapping
- debugnik 11mo agoDid you mix up unsigned and signed by mistake? Because in C and C++, the wrapping one is unsigned and the here-be-dragons-on-overflow one is signed.
- alpinisme 11mo agoOh jeeze. I can’t believe I flipped that. I find myself wishing I could delete my comment.
- sltkr 11mo agoNo, it's the opposite. UNSIGNED overflow wraps around. SIGNED overflow is undefined behavior. This leads to fun behavior. Consider these functions which differ only in the type of the loop variable: int foo() { for (int i = 1; i > 0; ++i) {} return 42; } int bar() { for (unsigned i = 1; i > 0; ++i) {} return 42; } If you compile these with GCC with optimization enabled, the result is: foo(): .L2: jmp .L2 bar(): mov eax, 42 ret That is, foo() gets compiled into an infinite loop, while the loop in bar() is eliminated instead. This is because the compiler may assume only in the first case that i will never overflow.