Course contentsShow
← C
Lesson 165 of 1,2193. Operators and ExpressionsFree lesson

Common pitfall: `=` vs `==`

Common pitfall: = vs ==

What you'll learn: You will learn how to avoid the most frequent logic error in C by distinguishing between giving a value to a variable and checking if two values are the same.

The Twin Symbols

In English, the word "equals" is flexible. You might say "Let xx equal 5" or ask "Does xx equal 5?" In C, these are two completely different operations. Using the wrong one won't always trigger a compiler error, but it will make your program behave in very strange ways.

= is an Action (Assignment)

Think of the single equals sign = as an arrow. It takes the value on the right and shoves it into the variable on the left. It is a command: "Make this happen."

int score = 10; // Action: The score is now 10.

== is a Question (Equality)

The double equals sign == is a scale. It looks at the left side and the right side and asks, "Are these currently balanced?" It returns 1 (True) if they match and 0 (False) if they don't. It doesn't change anything; it only observes.

Why the Mix-up is Dangerous

The real trouble happens inside if statements. In C, any non-zero value is treated as "True." If you accidentally use = instead of ==, you aren't asking a question; you are performing an action that almost always results in "True."

int status = 0;

// WRONG: This sets status to 1, then evaluates to true!
if (status = 1) { 
    printf("This will always run, even if it shouldn't.");
}

// CORRECT: This asks if status is 1.
if (status == 1) { 
    printf("This only runs if status is actually 1.");
}

In the "wrong" example above, the program changes status to 1 right inside the if condition. Because 1 is considered "True," the code block runs every single time, regardless of what the variable was before.

The Mental Shortcut

To keep them straight, try reading = as "gets" and == as "is equal to."

  • x = 5; (x gets five)
  • if (x == 5) (if x is equal to five)

Key takeaway

Use = to assign a value and == to compare two values.