Why is &&
preferable to &
and ||
preferable to |
?
I asked someone who\'s been programming for years a
To explain very clearly what this means (even though the other answers hint at it - but probably use terminology you don't understand).
The following code:
if (a && b)
{
Foo();
}
Is really compiled to this:
if (a)
{
if (b)
{
Foo();
}
}
Where the following code is compiled exactly as it is represented:
if (a & b)
{
Foo();
}
This is called short-circuiting. In general you should always use &&
and ||
in your conditions.
Bonus Marks: There is one scenario when you shouldn't. If you are in a situation where performance is crucial (and this is nano-seconds crucial) only use short-circuiting when you must (e.g. null
checking) - as a short-circuit is a branch/jump; which could result in a branch-misprediction on your CPU; an &
is much cheaper than &&
. There is also a scenario where short-circuiting can actually break logic - have a look at this answer of mine.
Diatribe/Monologue: Regarding the branch mis-prediction that most blissfully ignore. Quoting Andy Firth (who has been working on games for 13 years): "This may be lower level that people think they need to go... but they'd be wrong. Understanding how the hardware you're programming for treats branches can affect performance to a HUGE degree... far more than most programmers may appreciate re: death by a thousand cuts."
Here is a benchmark for the non-believers. It's best to run the process in RealTime/High to mitigate the scheduler having an effect: https://gist.github.com/1200737