I
last month
Iancountry asked

What’s the difference between = and == in C++?

Abhay Jajodia
Expert
last month
Abhay Jajodia answered

Hello Ian, really nice question.

In C++, = and == look almost the same, but they do completely different things.

  • = is the assignment operator
    It’s used to give a value to a variable.

    int x;
    x = 3;    // x gets the value 3
    
  • == is the equality operator
    It’s used to compare two values and check if they are the same.

    if (x == 3) {
        // this runs only if x is equal to 3
    }
    

So in an if statement:

if (i == 3) {
    // checks: is i equal to 3?
}

you’re asking a question: “Is i equal to 3?”
The result is either true or false.

If you accidentally write:

if (i = 3) {
    // this is NOT a comparison
}

you are assigning 3 to i. The assignment itself evaluates to 3, which is treated as true in C++, so the if condition will always be true. That’s almost never what you want and can cause very confusing bugs.

So the short rule is:

  • use = to set a value

  • use == to check a value

If you have further questions, I'm here to help.

C++
This question was asked as part of the Learn C++ Basics course.