Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is C++ underflow/overflow behaviour considered undefined?

Tags:

c++

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?

like image 879
user87166 Avatar asked Nov 16 '14 12:11

user87166


1 Answers

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.

like image 79
The Paramagnetic Croissant Avatar answered Sep 20 '22 12:09

The Paramagnetic Croissant