Course contentsShow
← C
Lesson 241 of 1,2194. Control FlowFree lesson

Relational operators: == and !=

Relational operators: == and !=

What you'll learn: How to use the "is equal to" and "is not equal to" operators to compare two values in C.

The Digital Scale

Imagine you have a traditional balance scale. If you put a 5lb weight on the left and a 5lb weight on the right, the scale sits perfectly level. In programming, we need a way to ask the computer, "Are these two things perfectly level?"

In C, we use the == operator (two equals signs) to ask this question. It is vital to use two signs because a single = is used for assigning a value to a variable. If = is a command ("Make this happen!"), then == is a question ("Is this true?").

Equality (==) and Inequality (!=)

There are two primary ways we compare equality:

  1. The Equality Operator (==): This returns true if the values on both sides are identical.
  2. The Inequality Operator (!=): This uses an exclamation point (which often means "not" in programming). It returns true if the values are different.

When you use these operators, the computer evaluates the expression and results in a 1 (true) or a 0 (false). C uses these numbers to decide whether to run a specific block of code.

Seeing it in Action

Let’s look at how these behave in a simple scenario involving a secret PIN.

#include <stdio.h>

int main() {
    int secretPin = 1234;
    int userGuess = 5555;

    // Is the guess exactly the same as the secret?
    if (userGuess == secretPin) {
        printf("Access granted!\n");
    }

    // Is the guess different from the secret?
    if (userGuess != secretPin) {
        printf("Access denied. Wrong PIN.\n");
    }

    return 0;
}

In the code above, userGuess == secretPin evaluates to false because 5555 is not 1234. However, userGuess != secretPin evaluates to true, so the "Access denied" message will appear on the screen.

Avoid the Trap

The most common mistake for new C programmers is typing if (x = 10) when they mean if (x == 10). The version with one equals sign actually changes the value of x to 10 instead of checking it! Always double-check your comparison operators to ensure you are asking a question rather than giving an order.

Key takeaway

Use == to check if two values are the same and != to check if they are different.