Comparison operators

We are close to be able to write programs with conditions (if statements), but before we go there, let's talk about comparison operators: how to check if something is greater than, less than, or equal to something else.

No special boolean type

C does not have a real boolean type (the one that can hold true or false values). Instead, if an expression evaluates to 0, it's considered to be false, otherwise it's true. All comparison operators return 1 for true, and 0 for false, but in the context of an if condition we'll talk about on the next page, any non-zero value – not only 1 – will be understood as "true".

Comparisons

To compare two numbers, you can use the regular comparison operators: <, >, <= (less or equal), >= (greater or equal), and... == which means "equal". Note it's ==, and not =: the single = is an assignment operator. It's so confusing that the bugs caused by using = where == is supposed to be are very common; we'll need to make sure to be careful here. There is also a "not equal" operator written as !=.

An example will help. Run this code:

#include <stdio.h>

int main() {
	printf("is 5 greater than 2? %d\n", 5 > 2);
	printf("is 5 equal to 2?     %d\n", 5 == 2); /* note the ==, not = */
	printf("is 5 less than 2?    %d\n", 5 < 2);
	return 0;
}

Now that you know how comparison operators work, we can go straight to conditional statements!