Either-or decisions are easy. They’re similar to the 1 or 0 of low-level programming: True/False, On/Off, Yes/No. When a third element appears, decision-making becomes more complex. To put it another way: That third element can drive both the programmer and the program crazy.
For example, consider a situation where a chunk of code must be executed when this condition is met:
The value of x is equal to 38
or
The value of y is in the range of 10 to 15
Translating that requirement directly into a if statement looks something like this:
if( x==38 || y>=10 && y<=15 )
That statement reads, left-to-right, like the condition stated above. As a seasoned programmer, however, I don't blindly trust multiple conditions within an if statement. Normally I'd hurriedly wrap parentheses around part of the equation, but I'll let this one go for demonstration purposes. Here's sample code:
#include <stdio.h> int main() { int x,y; printf("Enter a value for x: "); scanf("%d",&x); printf("Enter a value for y: "); scanf("%d",&y); if( x==38 || y>=10 && y<=15 ) puts("The condition is acceptable"); return(0); }
Below is a sample run using the values 38 for x
and 12 for y
, which should meet both conditions, with x
at 38 and the value of y
between 10 and 15.
Enter a value for x: 38
Enter a value for y: 12
The condition is acceptable
And here's a sample run using the values 5 and 9, which shouldn't meet the condition:
Enter a value for x: 5
Enter a value for y: 9
Other sample runs demonstrated that the code works, which is good, but it's not an excuse to be sloppy or assume anything.
If you have compiler warnings on, you'll see a message appear whenever you attempt to use more than one logical operator within an if comparison:
Line 12: warning: suggest parentheses around && within ||
The parentheses solution is this:
if( x==38 || (y>=10 && y<=15) )
In this case, however, the parentheses aren't really needed thanks to the order of precedence: The &&
operator ranks higher than the ||
operator, and associativity goes left-to-right. Therefore the parentheses are unnecessary. They do, however, make the code more readable.
My advice is to use parentheses whenever you're in doubt, which could imply all the time. Don't worry about any scourge attached to the parenthetical solution; if it works, and especially if it's more readable, consider it good.