The equality operator ==
What you'll learn: How to use the double equals sign to check if two values are identical without accidentally changing them.
The common confusion
In English, the word "equals" is a bit of a multitasker. When we say "x equals 5," we might mean we are making x be 5, or we might be asking if x is already 5. In C programming, these are two completely different actions.
You have already used the single equals sign (=) for assignment, which acts like a bucket loader, dumping a value into a variable. The double equals sign (==), however, is the equality operator. It doesn't change anything; it simply looks at two items and reports back: "Yes, these are the same" or "No, they are different."
The "Scale" analogy
Think of the == operator as a balance scale. You place a value on the left and a value on the right. The scale doesn't melt the items together; it just weighs them to see if they match.
If the two sides are equal, the expression evaluates to 1 (which C interprets as True). If they are different, it evaluates to 0 (which C interprets as False).
Seeing it in code
Here is how you might use == to check a user's secret code or verify a calculation:
#include <stdio.h>
int main() {
int secretPIN = 1234;
int enteredPIN = 1234;
int wrongPIN = 9999;
// This will result in 1 (True) because they match
printf("Is the PIN correct? %d\n", enteredPIN == secretPIN);
// This will result in 0 (False) because they do not match
printf("Is the wrong PIN correct? %d\n", wrongPIN == secretPIN);
return 0;
}
The "Double-Check" rule
The most common mistake for beginners is using = when they mean ==. If you write if (x = 5), you are actually setting x to 5, which usually results in a program that behaves very strangely. Always remember:
- Use
=to assign (give a value). - Use
==to compare (ask a question).
Think of the second equals sign as a "double-check." You aren't just telling the computer something; you are asking it to verify that two things are identical.
Key takeaway
Use == to test if two values are equal; it returns 1 for true and 0 for false.