Lesson 3.10. Comparison operators

In C, there are operators for comparing two entities: Is a smaller than b? These operators are mostly used in the conditional structures we will see later:

if (a>b)
  ...
else 
  ...

Comparison operators

There are 6 comparison operators in C:

Operator name Example Type
== is equal to a == b binary
!= is not equal to a != b binary
> greater than a > b binary
< less than a < b binary
>= greater than or equal to a >= b binary
<= less than or equal to a <= b binary

These operators can only return two values:

Note: the result is always of type int, whatever the type of the operands.

Do not confuse the assignment operator = and the comparison operator ==.
Do not reverse the characters:
>= and != are operators,

=> et =! are not operators.

Quiz

What is the value of the variable x after this instruction?

x = 12 > 8;
Check Bravo! A comparison operator can only return 1 or 0. Try again...

What should be the type of the variable x?

x = 12.5 <= 11.5;
Check Bravo! The type returned by the comparison operators is always int Try again...

What is the greater than or equal to operator?

Check Bravo! The equal sign must be after the upper sign. Try again...

What is the operator to test if two variables are equal?

Check Bravo! Do not confuse the assignment operator = with the comparison operator ==. Try again...

What does the following program display?

a = 12;
printf ("%d", a == 16);
Check Bravo! Comparison is false, it displays 0. Try again...

What does the following program display?

a = 12;
printf ("%d", a != 16);
Check Bravo! This time, the test is true, it displays 1. Try again...

What does the following program display?

printf ("%d", (5 > a) <= 3 );
Check Bravo! The comparison (5 > a) can only return 0 or 1, which will always be less than 3. Try again...

See also


Last update : 11/04/2022