Practice of checking 'trueness' or 'equality' in conditional statements - does it really make sense?
Posted
by Senthil
on Stack Overflow
See other posts from Stack Overflow
or by Senthil
Published on 2010-04-10T06:55:41Z
Indexed on
2010/04/10
7:13 UTC
Read the original article
Hit count: 260
conditional-statements
I remember many years back, when I was in school, one of my computer science teachers taught us that it was better to check for 'trueness' or 'equality' of a condition and not the negative stuff like 'inequality'.
Let me elaborate - If a piece of conditional code can be written by checking whether an expression is true or false, we should check the 'trueness'.
Example: Finding out whether a number is odd - it can be done in two ways:
if ( num % 2 != 0 )
{
// Number is odd
}
or
if ( num % 2 == 1 )
{
// Number is odd
}
When I was beginning to code, I knew that num % 2 == 0
implies the number is even, so I just put a !
there to check if it is odd. But he was like 'Don't check NOT conditions. Have the practice of checking the 'trueness' or 'equality' of conditions whenever possible.' And he recommended that I use the second piece of code.
I am not for or against either but I just wanted to know - what difference does it make? Please don't reply 'Technically the output will be the same' - we ALL know that. Is it a general programming practice or is it his own programming practice that he is preaching to others?
© Stack Overflow or respective owner