(x == 100) ???

Hey guys im just wondering why when i say the following:

if (x == 2)
cout << "x is 2";

why do i need 2 "==" in the (x == 2) why cant i just say (x = 2). what is the point of having this extra = sign.

Thanks guys for the help.
Last edited on
closed account (o3hC5Di1)
Hi there,

There is actually a big difference between the two.

= is the assignment operator , it is used to assign a value to a variable:
x=2; //x now holds the value 2

== is the equality operator it compares its left and right operand and returns true or false depending on if they are identical or not.

The assignment operator actually returns a reference to the variable you assigned to, so when you write:

if (x=2)

What happens is that x now holds the value 2 and if() will check whether x is 0 (false) or not (true).
In this case, you just made x hold the value two, so the if statement will always be true.

Hope that makes helps.

All the best,
NwN
See operators:
http://www.cplusplus.com/doc/tutorial/operators/

'=' is assignment
'==' is a comparison
== is also commonly known as the equal to operator, what it does is very simple, it compares the values on each side for example:
is 5 equal to 5? (5 == 5)
Yes, 5 is indeed equal to 5.
returns True.
is 5 equal to 6? (5 == 6)
No, 5 is definitely not equal to 6.
returns false.
Thanks guys your answers helped me to understand it better.
and i'm suggesting you learn the basics for C++ first. you can find it in this site...
Topic archived. No new replies allowed.