Sep 27, 2013 at 4:20pm UTC
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
Sep 27, 2013 at 4:21pm UTC
Sep 27, 2013 at 4:25pm UTC
There is actually a big difference between the two.
= is the assignment operator , it is used to assign a value to a variable:
//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:
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,
Sep 27, 2013 at 4:29pm UTC
== 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.
is 5 equal to 6?
(5 == 6)
No, 5 is definitely not equal to 6.
Sep 27, 2013 at 4:40pm UTC
Thanks guys your answers helped me to understand it better.
Sep 27, 2013 at 7:13pm UTC
and i'm suggesting you learn the basics for C++ first. you can find it in this site...