Skip to main content

Section 9.3 Relational and Equality Operators

We have already learned about several operators for numbers:
  • +, -, * addition, subtraction, and multiplication (integers and floats)
  • / integer division for integers and floating point division for floats
  • % remainder (modulus) of an integer division
Next, we’ll learn about relational and equality operators that serve to compare the values of two quantities:
  • <, > less than and greater than operators
  • <=, >= less than or equal to, greater than or equal to
  • != not equal to
  • == equal to (note the double equal sign; the single equal sign = has already been ’used up’ for our assignment operator)

Investigate 9.1.

Which of the following variables would C interpret as "true"? For example, if each variable was placed in the following code’s if statement as "variable", would the program output "True" or "False"?
  1. int a = -1
    
  2. char b = 'b'
    
  3. float c = 0.0
    
  4. int d = 4000
    
if (variable){
  printf("True")
}
else{
  printf("False")
}
A true logical relation evaluates to 1, whereas a false relation evaluates to 0. Examples:
  • Suppose x has the value 3.5. Then (x <= 5.0) evaluates to 1.
  • Suppose next that x has the value 7. Then (x <= 5.0) evaluates to 0.
  • (age == 30) evaluates to 1 if indeed age has the value 30, otherwise it evaluates to 0.
Note: Instead of (x <= 5.0) you could also write (5.0 >= x), and instead of (age == 30) you could just as well write (30 == age).

Investigate 9.2.

Does the following statement, which is comparing two characters, evaluate to true or false, according to C?
('A' > 'a')
Let’s look at an example.

If you cannot see this codecast, please click here.

Aside: Video Description.