What's wrong with a simple
= [doing double duty as both a comparison and assignment operator]? The same thing that's wrong with it in
C,
Java,
Perl, and, for that matter, the large majority of languages with the notable exception of
BASIC.
In C, the equality and comparison operators are == and = , respectively. This tends to cause trouble for novice and experienced programmers alike:
/*
Example of equality-comparison confusion in C.
Note that the same operator is used in both cases,
once correctly, once incorrectly.
*/
if (defcon = 666)
{
launch_missile();
launches = launches + 1;
}
Clearly the
intended purpose of this code is to check for a certain
defcon, and, finding it, execute the
launch_missile() function. However, the
programmer used
=, the assignment operator, not
== , the comparison operator. Thus, the
if-test
assigned a value of
666 to
defcon. Because the
value of the act of assignment is the value it assigned, the
if-test evaluated as
666 (which, being nonzero, is interpreted as 'true')... and thus the
function gets called regardless of the initial value of the test
variable.
Pascal, for all its faults, appears to make the more rational choice in operator typography. Consider the same code in Pascal:
(*
Example of equality-comparison confusion in Pascal.
Note that the same operator is used in both cases,
once correctly, once incorrectly.
*)
if defcon = 666 then
begin
launch_missile;
launches = launches + 1
end;
This code launches the missile
only if
defcon is indeed
666. It does not properly
increment the
launches variable, but it would seem that this is a minor problem compared to the alternative. (Furthermore, the
compiler will catch that particular error.)
We are taught as early as first grade that = is the symbol for equality, and it makes more sense to make assignment the exception rather than the rule.
N-Wing points out that in Java, the test would fail because you're attempting to assign an integer to a boolean. However, the problem would return if one were testing a boolean variable. On the other hand, how often do you check booleans for equality? Normally, you would just do if(z) or if(!z).