4 ms·
I don't understand the example bool g(bool b) { if (b) return true; int unused = 1 / 0; return false; } Shouldn't it be optimized to
by dkarapetyan 10y ago
I don't understand the example
bool g(bool b) {
if (b)
return true;
int unused = 1 / 0;
return false;
}
Shouldn't it be optimized to
bool g(bool b) {
return b;
}
instead of
bool g(bool b) {
return true;
}
- nikic 10y agoDivision by zero is undefined behavior, so the compiler is free to assume that the b==false branch is unreachable.
- dkarapetyan 10y agoI see.
- choosername 10y agoIt would also be reasonable to remove the declaration as the variable is "unused".
- legulere 10y agoint unused = 1 / 0; is undefined behaviour. The compiler can replace it with anything it wants. Like for instance a return true. Compilers usually (ab-)use this to remove branches.
- adrianratnapala 10y agoNo need to for parentheses around "ab" in abuse. This is just bad behaviour from compilers trying to optimise for benchmarks. The right thing to do is to issue an error or warning, and then not make absurd assumptions about other variables. A good explanation of all this can be found here: http://c9x.me/compile/bib/ubc.pdf http://c9x.me/compile/bib/ubc.pdf
- legulere 10y agoI guess the problem with issuing warnings is that dead code can also contain undefined behaviour, so the compiler would probably produce lots of false positives.