CodeBlanks Logo Icon CodeBlanks

Comparison operators

Learn to compare values with ==, !=, <, >, <= and >=.

Comparison operators

C has six comparison operators: == (equal), != (not equal), < (less), > (greater), <= (less or equal), >= (greater or equal).

int a = 5, b = 10;
int c = (a < b);  /* c = 1, true */
int d = (a == b); /* d = 0, false */

The result is an int: 1 for true, 0 for false. Before C99 C had no true and false keywords; numeric 1 and 0 are used.

Result is int: 1 or 0

In C the comparison result is an int. It is 1 for true, 0 for false. This value can be stored in a variable or used in an if condition.

int r = (5 > 3);   /* r = 1 */
int s = (5 < 3);   /* s = 0 */
if (5 >= 5) { /* true, 1 */ }

This is why writing if (number) works: any non-zero number counts as true. This behavior is specific to C and should be used with care.

Practice Print comparison results

Define int a = 7, b = 5;. With four printf calls print a > b, a == b, a != b and a <= b on separate lines. Output should be 1, 0, 1, 0.

Starter code

main.c
#include <stdio.h>

int main(void) {
    int a = 7, b = 5;
    /* print a > b, a == b, a != b, a <= b */
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int a = 7, b = 5;
    printf("%d\n", a > b);
    printf("%d\n", a == b);
    printf("%d\n", a != b);
    printf("%d\n", a <= b);
    return 0;
}

Expected output

1
0
1
0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match operators to their meanings

Term Meaning
== equal
!= not equal
< less
> greater

2 What is the result of 5 > 10?

  • 0 Correct answer
  • 5
  • 1
  • 10

Explanation: 5 is not greater than 10, so the result is 0 (false).

3 Greater or equal operator

Question
int a = 7, b = 5;
if (a ____ b) { /* true */ }
Answer
int a = 7, b = 5;
if (a >= b) { /* true */ }

Explanation: >= means greater or equal.

All lessons in Beginner