I was coding away today when I came across something I do all the time without thinking as wondered if it had any after affects.
Here are two ways of doing the same thing
if(foo != true)
{
bar ++;
}
if(foo == true)
{
}
else
{
bar ++;
}
Now I know the compiler would probably optimise this to the same thing but I want to know the difference because you cannot always count on them.
My question is really would the second option incur some kind of penalty because it adds another command to the check ?
Yes it was a typo.
Neither is good. Apart from the fact that the second contains a typo (
=instead of==), comparing booleans to constants is just redundant. Just test their values directly:First of all, it removes the possibility of creating bugs though typos (as you have graciously shown). But apart from that it’s just more logical.
(Note however that it’s not more efficient. The statements are strictly equivalent.)