The
similarity of the assignment and equality comparison operators
It is especially important to note
that the equal sign = is not used for comparing
whether two things are equal; you need ==.
These are a major source of confusion for beginners.
For example, if one wanted to define
a loop that repeated while x was equal to `false', it would be wrong
to write:
while
(x = false)
{
//...
}
Since what (x = false) does is to assign
the value `false' to the variable x. It is not comparing the value inside
variable x with the value `false'.
The annoying thing about this is that
the compiler will accept it, as it is perfectly valid Java syntax. It will
simply give totally wrong and confusing results. This is because an assignment
statement evaluates to a value itself. That is, writing
while (x =
false)
is equivalent to:
x = false;
while (x)
which is equivalent to:
while (false)
The code should be written as follows
(i.e. using the test for equality operator ==):
while
(x == false)
{
//...
}
It is almost certain that you will make
this mistake, more than once, during this module. Many people who have
been programming professionally for years still make this mistake all the
time. It is a poorly designed feature of the language, but retained to
keep compatibility with C++ and C syntax.
Back
to top
.
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|