C Tutorial (12) : Logical operators

Sometimes the relational operators simply can’t express all the testing conditions. For example, if you wanted to test whether a numeric or character variable is within a certain range, you would have to use two if statements, like this:

if (age >= 21) /* See if 21 <= age <= 65 */ 
{ 
if (age <= 65)
{
  printf("The age falls between 21 and 65.\n");
}
}

By using the logical operators , you can combine more than one relational test in a single if statement to clarify your code.

The logical operators combine relational operators.

Three logical operators exist. Sometimes logical operators are known as compound relational operators because they let you combine more than one relational operator.

&&                                 AND
||                                 OR
!                                  NOT

Logical operators appear between two or more relational tests.

if ((age >= 21) && (age <= 65)) { and if ((hrsWorked > 40) || (sales > 25000.00)) {
and
if (!(isCharterMember)) {

The entire expression following the if statement requires parentheses. This is not allowed:

if !isCharterMember {                      /* Not allowed */

Both sides of the && must be true for the body of the if to execute.

One side or the other side of the || must be true (and they both can be true as well). If either side is true, the result can occur.

The ! (not) operator reverses a true or a false condition. True becomes false, and false becomes true. Limit the number of ! operators you use. You can always rewrite a logical expression to avoid using ! by reversing the logic. For example, the following if:

if ( !(sales < 3000)) { is exactly the same as this if: if ( sales >= 3000) {

As you can see, you can remove the ! and turn a negative statement into a positive test by removing the ! and using an opposite relational operator.

Avoiding the Negative

Suppose you wanted to write an inventory program that tests whether the number of a certain item has fallen to zero. The first part of the if might look like this:

if (count == 0) {

Because the if is true only if count has a value of 0, you can rewrite the statement like this:

if (!count) { /* Executes if’s body only if count is 0 */

Again, the ! adds a little confusion to code. Even though you might save some typing effort with a fancy !, clearer code is better than trickier code, and if (count == 0) { is probably better to use, despite the microsecond your program might save by using !.

Using the && operator, the following program prints one message if the user’s last name begins with the letters P through S, and it prints another message if the name begins with something else.

/* This program asks for a last name, and if the user has a last name that starts with a letter between P and Q, they will be sent to a special room for their tickets. */

#include 

main()
{
// set up an array for the last name and then get it from the user

char name[25];
printf("What is your last name? "); 
printf("(Please capitalize the first letter!)\n"); 
scanf(" %s", name);

//For a string array, you don't need the &
if ((name[0] >= 'P') && (name[0] <= 'S'))
{
printf("You must go to room 2432 "); 
printf("for your tickets.\n");
}
else
{
printf("You can get your tickets here.\n");
}
return 0;
}

lowercase p, if you wanted to check for either, you could use the following, more complicated, logical statement:

if (((name[0] >= 'P') && (name[0] <= 'S')) || (name[0] >= 'p') && (name[0] >= 's')))

Note : How would the program be different if the && were changed to a ||?  Everybody would be sent to Room 2432. Any letter from A to Z is either more than P or less than S. The test in the preceding program has to be && because Room 2432 is available only to people whose names are between P and S.

Note : You can combine more than two relational operators with logical operators, but doing too much in a single statement can cause confusion. This is a little too much:

if ((a < 6) || (c >= 3) && (r != 9) || (p <= 1)) {

Try to keep your combined relational tests simple so that your programs remain easy to read and maintain.

The Order of Logical Operators

Because logical operators appear in the order of operators table, they have priority at times, just as the other operators do. Studying the order of operators shows you that the && operator has precedence over the ||. Therefore, C interprets the following logic:

if (age < 20 || sales < 1200 && hrsWorked > 15) {
like this:
if ((age < 20) || ((sales < 1200) && (hrsWorked > 15))) {

Use ample parentheses. Parentheses help clarify the order of operators. C won’t get confused if you don’t use parentheses because it knows the order of operators table very well. However, a person looking at your program has to figure out which is done first, and parentheses help group operations together.

if-else & Relational operators < Prev   Next > Conditional, Increment-Decrement operators

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s