
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 valueuse
==to check a value
If you have further questions, I'm here to help.
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer
