+ 1
What's the difference between "=" and "=="
4 Answers
+ 3
= assigns a value to a variable e.g. int a = 56;
== compares 2 values and returns a boolean if they are equal or not e.g. 4 == 5 would be false, 67 == 67 would be true
+ 2
TurtleShell is spot on. Just to add to their excellent answer:
The following code prints "Five", because a = 5, assigns 5 to the variable a, and then evaluates to 5, so if (5) is executed, which in C, equates to true, as non zero values are all true, and only 0 is false!
int a = 4
if (a = 5)
{
printf("Five");
}
else
{
printf("Not Five");
}
The following code prints "Not Five"
int a = 4
if (a == 5)
{
printf("Five");
}
else
{
printf("Not Five");
}
This is why some people advocate writing it like this:
int a = 4
if (5 == a)
{
printf("Five");
}
else
{
printf("Four");
}
Because if you make a mistake and use if (5 = a), instead of if (5 == a), the compiler will moan! But if (a = 5), the compiler allows.
+ 2
Both are not same, = is an Assignment Operator it is used to assign the value of variable or expression, while == is an Equal to Operator and it is a relation operator used for comparison (to compare value of both left and right side operands).