3 ms·
Technically (which is the best kind), yes.
by valleyer 3y ago
Technically (which is the best kind), yes.
- LegionMammal978 3y agoAt least the print and flush will occur before whatever the compiler decides to do with the UB, unless it's one of those purely-theoretical impelementations that can prove that those functions eventually return.
- readams 3y agoI know you already know this but wanted to clarify that technically ub can "go back in time" and not print those earlier statements.
- deleted 3y ago[deleted]
- jcranmer 3y agoI/O is considered a visible side effect, so compilers can't optimize away the call to the print and flush, even if UB happens immediately afterwards.
- Dylan16807 3y agoI'm pretty sure they can. In practical terms, compilers are allowed to reorder calculations, and the print might as well not be there if it's after a crash. In theoretical terms, once UB is guaranteed to happen then your program execution is no longer valid, the entire execution, and the compiler is not bound by any rules whatsoever.
- SpaghettiCthulu 3y agoBut if the compiler can prove that the code causing the UB will be reached regardless of the IO action, could it not assume that the IO action can never be reached, progagating the UB before it?
- lights0123 3y agoCorrect, since unless the program is compiled with -nostdlib, the compiler can assume you're using its printf implementation which does not alter code flow (such as by exit(), longjmp, or exceptions in C++)
- SpaghettiCthulu 3y agoThat's still irrelevant. The compiler can look at any code like this: ``` invokeUB(); doSomething(); ``` and regardless of what `doSomething()` does (it need not be a function call), remove the call entirely if it so chooses. The reason for this is that `doSomething()` cannot be reached except after `invokeUB()`. Because undefined behaviour can be considered unreachable, `invokeUB()` can be too. Therefore, to the compiler, it is impossible to ever reach `doSomething()`, and thus it may be safely eliminated.
- gizmo686 3y agoC compilers are allowed to assume that UB never happens. This means that if there is a code path that results in UB, the compiler can "know" that path will never be taken and simply not compile it (or replace it with code that summons demons through your serial port)