Monday, June 1, 2009

Logical AND & OR confusions

I have seen many people getting confused with logical AND and logical OR - especially when writing programs. This used to happen to me during my initial learning days with C programming.

Debug this:
if(string!=NULL || string != empty)
{
/* Use the string to do some work, say */
print(string);
}

The above condition will always execute - beware it might also cause an application crash.

What most programmers expect to do is:
if(string==NULL || string == empty)
{
/* Skip the operations */
}
else
{
/* Use the string to do some work, say */
print(string);
}

Which actually should have translated to:
if(!(string == NULL || string == empty))
{
/* Use the string to do some work, say */
print(string);
}

Which can be coded as:
if(string != NULL && string != empty)
{
/* Use the string to do some work, say */
print(string);
}

Note the logical AND.

If you think you get confused with AND/OR, don't worry you are not alone.

PS: This is similar to the rule ~(p or q) == (~p and ~q)

No comments: