Quote:
Originally Posted by Anais
omg, just wrote a huge long post about not getting why this bool kept always returning true, and then I happened to see that one of my if() statements was using the assign = operator instead of ==.
Why would that not throw a compiler error?
I demand digital blood!
Probably you are using a scripting language like JavaScript?
In most C-style languages, an assignment operation also produces a value. This is occasionally mildly useful in constructs like this:
Quote:
string line;
while ((line = streamReader.ReadLine()) != null) {
....
}
Or in chained assignments:
For the amount of grief it causes, IDK if it's worth it, but here we are. Nobody wants to make an alteration to C-style languages that might break existing code.
The problem in weakly-typed languages like JavaScript is that everything is "truthy", so things like 3 or 'banana' are true. (The only things that are not true in JavaScript are false, 0, '', null, NaN and undefined). Therefore the value produced by the assignment is silently cast to true.
In C#, which is mostly what I write in, something like this will not compile:
Quote:
int x = 1;
int y = 2;
if(x = y) {
...
}
But this will, because the assignment produces the desired bool type:
Quote:
bool x = true;
bool y = false;
if(x = y) {
...
}
But it does throw this compiler warning:
Quote:
Test.cs(50,17,50,25): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?
I also have the Resharper addon for Visual Studio, which underlines that "x = y" in the IDE and warns me about it when I mouseover.