Comparison And Logical Operators

Using a simple variable (as in the previous example) as a condition won't take you very far in your programming. In order to make more complex, real-world if statements, you'll want to utilize the various comparison and logical operators (Table 4.1).

Table 4.1. These comparison and logical operators are frequently used in conditionals and other control structures.
Comparison and Logical Operators
OperatorMeaning
>Greater than
<Less than
>=Greater than or equal to
>=Less than or equal to
==Equal to
!=Not equal to
&&and
||or
!not

The comparison operators are used with mathematical values, for example, to tell if one value is greater than, equal to, or less than another. Using these, the true/false status of a conditional can be based on more elaborate formulas:

if (age >= 18) {
   printf ("You are old enough to vote.");
}

The logical operators are used, often in conjunction with parentheses, to create compound conditions, such as a range:

if ( (age > 12) && (age < 20)) {
   printf ("Teenager alert!");
}

Special attention should be given to the equality operator (==). One of the most common mistakes programmers make—even the most seasoned ones—is to inadvertently use the assignment operator (=) in a condition:

if (var = 190) {...

The real intent of the conditional is to check if the value of var is equal to 190 (written as var == 190), which may or may not be true. The above, miswritten conditional, will always be true (as var can be assigned the value of 190).

One simple use of these operators is to print a message based on the value of a grade point average.

To use comparison and logical operators

1.
Create a new, blank C project in your text editor or IDE.

2.
Add the initial comments and code (Script 4.2):

/* gpa.c - Script 4.2 */
#include <stdio.h>
int main (void) {

Script 4.2. Thanks to the comparison and logical operators, a variable can be tested against several possible conditions.


3.
Declare and initialize a float variable:

float gpa = 3.8;

The gpa variable will store the value of a person's grade point average. For the initial run, it will be set to 3.8.

4.
Determine if the grade point average qualifies for graduating summa cum laude (with highest honors):

if (gpa >= 3.9) {
     printf ("You're graduating summa
 cum laude with a %0.2f GPA!
", gpa);
}

If the value of gpa is greater than or equal to 3.9 (a standard mark for summa cum laude), this print statement will be executed. If the value is less than 3.9, this print statement will be skipped.

5.
Determine if the grade point average qualifies for graduating magna cum laude (with great honors):

if ( (gpa >= 3.75) && (gpa < 3.9) ) {
     printf ("You're graduating magna
 cum laude with a %0.2f GPA!
", gpa);
}

Using the logical operator and parentheses, this conditional tests if gpa has a value greater than or equal to 3.75 but less than 3.9 (which is the start of summa cum laude). Because of the and (&&) operator, both conditions must be true in order for the entire condition to be true. If gpa is less than 3.75 or greater than or equal to 3.9, this conditional is false.

6.
Determine if the grade point average qualifies for graduating cum laude (with honors):

if ( (gpa >= 3.50) && (gpa < 3.75) ) {
 printf ("You're graduating cum
 laude with a %0.2f GPA!
", gpa);
}

The final conditional is like the one in Step 5, but uses different number values.

7.
Complete the main() function:

   getchar();
   return 0;
}

8.
Save the project as gpa.c.

9.
Compile and debug, as necessary.

10.
Run the executable application (Figure 4.3).

Figure 4.3. Different messages are printed based on the value of the gpa variable (compare with Figure 4.4).


11.
For comparison, change the value of gpa, recompile, and rerun the application (Figure 4.4).

Figure 4.4. Running the gpa application using a different value for the main variable.


✓ Tips

  • As the example is written, if gpa is not greater than 3.5, no message is printed at all. This will be rectified in the next example, or you could add a fourth conditional, printing a message if gpa is less than 3.5.

  • Remember never to compare the equality of floats. Due to the way computers represent this data type, two seemingly equal values may be off by the merest fraction. Similarly, the integer 2 and the float 2.0 may not equate!

  • Some programmers recommend reversing the values in a conditional when one literal value is used. For example:

    if (24 == hours) {...
    

    The benefit of this is that if you inadvertently use only one equals sign, an error message will be reported upon compilation (as you cannot assign the value of a variable to a number).

    The Perils of Precedence

    Just as you learned that the assignment and arithmetic operators have a precedence to them, so do the comparison and logical operators. Specifically, <, >, <=, and >= rank higher than either == or !=.

    In the greater scheme of things, the comparison operators have a higher precedence than the assignment operator (=) but a lower precedence than the arithmetic operators.

    Conversely, not (!) is above multiplication and division, whereas and (&&) and or (||) have a higher precedence than the assignment operators but a lower one than the relational operators. And && is higher than ||.

    Confusing? Yet bet. You can either memorize all of this—replicated in a table in Appendix B, “Resources”—or just use parentheses to enforce precedence: the easiest, most foolproof method.


  • To determine if two strings are the same, you would use the strcmp() function. This function, which is short for string compare, returns a number indicating the difference between two strings. If the returned value is 0, they are the same:

    if (strcmp(var1, var2) == 0) {...
    

    You'll learn more about this data type in Chapter 11, “Working with Strings.”


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset