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

Common mistake: assignment (=) vs equality (==)

Common mistake: assignment (=) vs equality (==)

What you'll learn: How to avoid the "accidental assignment" bug that causes conditional statements to behave unexpectedly.

The difference in symbols

In C, the single equals sign (=) and the double equals sign (==) do two completely different jobs. Think of the single equals sign as an action. It is the "assignment" operator, used to put a value into a box. If you write x = 5;, you are telling the computer, "Take the number 5 and shove it into the variable x."

The double equals sign is a question. It is the "equality" operator. If you write x == 5, you are asking the computer, "Is the value currently inside x the same as 5?" The computer answers this question with either a 1 (true) or a 0 (false).

The trap: Assignment inside an if

The most common mistake for beginners is using = when they mean == inside an if statement. Because of how C works, this won't usually trigger a compiler error, but it will make your program act very strange.

In C, an if statement evaluates whether the expression inside the parentheses is non-zero. If you accidentally perform an assignment inside an if, C will perform the action and then check the result.

#include <stdio.h>

int main() {
    int temperature = 20;

    // MISTAKE: Using = instead of ==
    if (temperature = 100) {
        printf("It is boiling!\n");
    }

    printf("The temperature is now: %d\n", temperature);
    return 0;
}

In the code above, the program won't check if the temperature is 100. Instead, it will set the temperature to 100. Since 100 is a non-zero number, the if statement treats it as "true" and prints "It is boiling!" even though the temperature was originally 20. Worst of all, your temperature variable has now been permanently changed.

Why this happens

C is designed to be flexible, and it allows you to chain assignments together. However, this flexibility means the compiler assumes you know what you are doing when you put an assignment inside a condition. To the computer, if (x = 5) is a valid command to "set x to 5, then tell me if 5 is true." Since 5 is not 0, it is always true.

Key takeaway

Always use == to compare two values; using = will overwrite your data and almost always evaluate to true.