I read about undefined behavior, and I'm not sure if this is just a compile-time function, or if it could happen at runtime.
I understand this example well (this is extracted from the Undefined Wikipedia behavior page ):
Example for 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 the opposite integer overflow is undefined behavior in C, the compiler may assume that if value >= 5 in the check string. Thus, if and calling the bar function can be ignored by the compiler, since if has no side effects and its condition will never be met. Therefore, the above code is semantically equivalent:
int foo(unsigned x) { int value = 5; value += x; return value; }
But this happens at compile 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 enter the user type MAX_INT - 100 ("2147483547" if 32 integer bits).
There will be an integer overflow, but AFAIK, this is the arithmetic logical unit of the processor that will make the overflow, so the compiler is not involved.
Is this behavior still undefined?
If so, how does the compiler detect overflow?
The best I could imagine was a CPU overflow flag. If so, does this mean that the compiler can do whatever it wants if the CPU overflow flag is set at any time at runtime?