== != =For those of you who aren't programmers, this is a slam at perhaps one of the worst programming language syntax decisions that has ever been made. You can read the above expression as "Equal equal is not equal to equals". Still lost?
In the C programming language (and derivatives such as C++, Java, JavaScript and C#) the way that you test to see if two variables are equivalent to each other is to use the "==" operator. For example:
if ( a == b ) { doSomething(); }
If you want to assign a value to a a variable you use the assignment operator "=". For example:
a = b;
Believe it or not, even folks who have been programming for years occasionally screw up and use the assignment operator "=" when they meant to use the test for equivalence operator ==. Here's an all too common example:
if ( a = b ) { doSomething;}
The line above sets the value of variable "a" to the value of variable "b". If "b" is not zero, then the function "doSomething()" will be invoked. Perhaps that's the behavior that the programmer desired, but I really doubt it.
According to the wikipedia article comparing the Pascal programming language to C:
"It is common for programmers new to C to accidentally put assignment expressions in conditional statements such asif (a = 10) { ... }, which will always execute because the assignment expressiona = 10has the value 10 ≠ 0 and is therefore considered "true" in C. Also note thatahas now got the value10, which may affect the following code. This kind of mistake cannot happen in Pascal, as assignments are not expressions; using the wrong operator will cause a compile error (and it's not likely that anyone would mistake the:=symbol for equality test)."
I have to take issue with this statement... It's not just programmers who are new to C. I made this mistake last week :-)
This mistake is so common that some programming editors will actually flag statements like this to warn the programmer. I've no idea how much time has been lost on this little syntactical monkey wrench, but I think it's probably quite a bit.
Long ago before I learned C I used Pascal. In Pascal the "=" operator is used to test for equality. If you want to set a value you used ":=". When reading this symbol out loud I'd always say "set equal to". For some reason, I don't ever remember confusing the two or knowing anyone else who ever confused the two.
The BASIC programming language is even simpler... the interpreter uses the context of where "=" appears in an expression to determine what it means. IF $A = 0 THEN is interpreted as a comparison. $A = 3 is interpreted as an assignment.
I don't know why the authors of C chose to use "==" and "=" in this way - but unfortunately that decision was inherited by most of the programming languages that are widely used today. Every programmer who includes some JavaScript on a web page might screw up and make this mistake... so just remember:
== != =
0 comments:
Post a Comment