The inequality operator !=
What you'll learn: How to use the != operator to check if two values are different from one another.
The "Odd One Out" Logic
In previous lessons, you learned how to use == to check if two things are identical. However, in programming, we often care more about when things don't match. This is where the inequality operator (!=) comes in.
Think of the != operator as a security guard at a private party. The guard has a list of banned individuals. If your name is not equal to a name on that list, you are allowed to pass. The operator asks a simple question: "Are these two values different?"
- If the values are different, the expression is True (represented as
1in C). - If the values are exactly the same, the expression is False (represented as
0in C).
Seeing it in Action
The != operator consists of an exclamation point (which often means "not" in programming) followed by an equals sign. There should be no space between them.
Here is how you might use it to check a user's PIN entry or a game state:
#include <stdio.h>
int main() {
int correctPin = 1234;
int enteredPin = 9999;
// Check if the entered PIN is NOT the correct one
if (enteredPin != correctPin) {
printf("Access Denied: The PINs do not match.\n");
}
int enemyHealth = 0;
// Check if the enemy is still alive (health is not zero)
if (enemyHealth != 0) {
printf("The battle continues!\n");
} else {
printf("Victory! The health is zero.\n");
}
return 0;
}
Why not just use ==?
You might wonder why we don't just use == and flip the logic. While possible, using != makes your code read more like natural English. It is much more intuitive to write "If the temperature is not 100, keep heating" than to write "If it is false that the temperature is 100."
This operator is particularly useful for "sentinel values"—special values used to signal the end of a process. For example, you might tell a program to keep processing data as long as the input != -1.
Key takeaway
The != operator returns true if its two operands are different and false if they are the same.