if (x < 4){
}
If Statement Skipping
Just a quick question...
In C++, will the compiler completely skip over an if statment if there is nothing inside the if block?
In other words, will the compiler not even evaluate an if statement such as this one:
because there is nothing inside the if block? I ask because I have an if statment in my program that whenever I put anything (doesn't matter what) inside of the if block, the program crashes, otherwise, everything is normal. The only explanation I can assume for this is that the compiler just doesn't care about the if statement anymore and isn't evaluating it. Anybody have confirmation on this?
Thanks,
Jeff
EDIT: Fixed Tags
If you have an if statement with nothing in it, and your compiler is optimising at all, that block will not show up in the compiled code, but will instead be optimized out.
In your specific example, I doubt any compiler would fail to optimize away the comparison in a release build [read: with optimizations]. A quick check reveals that VS.NET2003, without optimizations set, evaluates the comparison.
CM
CM
Quote:Original post by GodlyGamr
I ask because I have an if statment in my program that whenever I put anything (doesn't matter what) inside of the if block, the program crashes, otherwise, everything is normal.
Wow. You've got one serious problem if populating an conditional block causes a crash. About the only thing I can suggest is to do a make clean first, which would be like rebuild all in dev-c++.
Quote:
I ask because I have an if statment in my program that whenever I put anything (doesn't matter what) inside of the if block, the program crashes, otherwise, everything is normal.
Check for any memory access violations (indexing an out-of-bounds cell in an array, for instance) in your program. This is a possible cause.
To answer your original question, if the expression has no possible side-effects, then an optimizing compiler might not evaluate it at all. But remember that if your "if" statement is, for example
if (x++) {}
or
if (foo()) {}
it will always get evaluated.
Quote:it will always get evaluated.
Sort of. The code will be executed, but the if itself will be ignored. if(foo()) {} should produce the exact same assembly as foo();
Quote:Original post by eyal
But remember that if your "if" statement is, for exampleif (x++) {}
orif (foo()) {}
it will always get evaluated.
Not neccessarily. In particular, the if(x++) {} one can be optimized away entirely if you don't check the value of x again after that line. Its apparently called 'dead store removal.' I don't know all the rules, but I stumbled upon a discussion about that very issue a while back. This was part of it, but there were a few responses on another page I can't find anymore.
CM
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement