The exact problem is that =
and ==
are 2 completely different operations.
Say, for example, x
is a float value. Then the operation x=5
sets x
to 5
- and it also returns the value of x
.
So, if(x = 1870){...
sets x
to 1870
, and the operation, as a result, returns 1870
too, so you are practically doing if(1870){...
. And that’s why you get an error - if
statement expects a boolean value, but gets a float - and there is no direct obvious way to convert a float value to a boolean, so it just errors at you instead.
That’s why doing something like x = y = z = 12345;
works - it gets resolved as x = (y = (z = 12345));
, then x = (y = 12345);
, then x = 12345;
, practically setting every value to the deepest one in the operation chain - which is the rightmost in this case.
This can be useful to crunch up code to make it smaller or look cool. For example if(x = x+1 == 20) ...
sets x to itself plus 1, and then compares that to 20, and does the if
statement based on the result. (although I personally don’t like doing stuff like that)
The ==
operation, however, does not set anything to anything, takes 2 arguments, and returns a boolean.
So, x == 1870
gets resolved into either true
or false
- exactly what if(...)
statement wants.
You could also combine both operations the other way around: myBool = x == 1870;
- this compares x
to 1870
and sets myBool
to either true
or false
depending on the result.
As far as I know, this is also the case in many other programming languages that differentiate the two operations.
Make sure to not repeat this mistake you made when comparing boolean statements - it will give no error, would set the left boolean to the right one’s value, and can easily cause a “what in the world is going on???” moment!