I understand that integer underflow and overflow are undefined.
However, given that C++ eventually compiles to assembly, isnt the behavior actually defined?
The bitwise representation stays the same, the integer format remains the same 0111..11 will always roll over to 1000..00, same for underflows, so why is it not considered defined behaviour?
About the assembly compilation, I was deriving from the rudimentary assembly we were taught in school, but code blocks gives
int x = INT_MAX;
int y = x+1;
compiles to
00401326 movl $0x7fffffff,0x8(%esp)
0040132E mov 0x8(%esp),%eax
00401332 inc %eax
00401333 mov %eax,0xc(%esp)
Now, regardless of the value of x, wont there always be an inc or a add instruction? So, where does the undefined behaviour arise?
However, given that C++ eventually compiles to assembly, isnt the behavior actually defined?
No, since the compiler decides what kind of assembly it emits. If the compiler wishes, it can generate assembly that erases your hard disk if it encounters undefined behavior.
(Actually, it may not even be true that "C++ eventually compiles to assembly". There exist C++ interpreters, for example - the Standard doesn't specify how/into what format C++ should compile.
One of the reasons why the creators of the Standard decided to leave it undefined is – as almost always – the opportunity for optimizations. If signed overflow is UB, then the compiler can, for instance, assume that x + 1 > x
is always true and generate simpler/shorter/faster code that relies on this precondition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With