I was typing this code, and when I used an equal sign it didnt work. But then I put a double equal sign and then it worked. |
The important thing is that
=
on its own will
change the value of something. The double equals
==
simply tests the value, but leaves it
unaltered.
For example,
1 2 3 4 5 6 7 8 9 10
|
int x = 5;
int y = 17;
// test to see whether x is equal to y.
cout << (x == y) << endl;
cout << "x: " << x << " y: " << y << endl;
// change x so that its value is now the same as y.
cout << (x = y) << endl;
cout << "x: " << x << " y: " << y << endl;
|
Output:
0
x: 5 y: 17
17
x: 17 y: 17 |
Explanation of output
0 means
false
, x is not equal to y.
original x and y are displayed.
17 means
true
. It is also the value of the expression, that is the value of x.
New values of x and y are displayed.
When it comes to conditional expressions, such as
if (something)
or
while (something)
, we normally think in terms of
true
and
false
. But the compiler will also treat a zero value as meaning
false
, and any non-zero value (such as 17 in the example) as meaning
true
.
Also, you can do this:
cout << (5 == 3) << endl;
But this is an error:
cout << (5 = 3) << endl;
The first is comparing 5 and 3.
The second tries to change the value of 5 to make it 3. That doesn't make any sense, either to the compiler, or to us.