I was reading about undefined behavior, and I'm not sure if it's a compile-time only feature, or if it can occurs at execution-time.
I understand this example well (this is extracted from the Undefined Behavior page of Wikipedia):
An example for the C language:
int foo(unsigned x) { int value = 5; value += x; if (value < 5) bar(); return value; }
The value of
x
cannot be negative and, given that signed integer overflow is undefined behavior in C, the compiler can assume that at the line of the if checkvalue >= 5
. Thus theif
and the call to the functionbar
can be ignored by the compiler since theif
has no side effects and its condition will never be satisfied. The code above is therefore semantically equivalent to:int foo(unsigned x) { int value = 5; value += x; return value; }
But this occurs at compilation-time.
What if I write, for example:
void foo(int x) {
if (x + 150 < 5)
bar();
}
int main() {
int x;
std::cin >> x;
foo(x);
}
and then the user type in MAX_INT - 100
("2147483547", if 32 bits-integer).
There will be an integer overflow, but AFAIK, it is the arithmetic logic unit of the CPU that will make an overflow, so the compiler is not involved here.
Is it still undefined behavior?
If yes, how does the compiler detect the overflow?
The best I could imagine is with the overflow flag of the CPU. If this is the case, does it means that the compiler can do anything he wants if the overflow flag of the CPU is set anytime at execution-time?