PHY3134 Computational
Physics
Hints and tips
Comments and questions to John Rowe.
a == b == c is not what you expect
People sometimes wish to compare three numbers for equality and try:
if ( a == b == c )
Unfortunately this doesn't do what you expect, instead it
is equivalent to:
if ( (a == b) == c )
The following occurs:
- (a == b) is an integer
expression which will evaluate to
either one or zero.
- This value is then checked for equality with c,
again producing the result one or
zero.
- Thus if c has
any value other than one or
zero the expression
a == b == c will always evaluate to
zero.
- If c has the value one
or zero
the expression will evaluate to either one or
zero
according to whether or not a equals
b.
- Either way it
won't do what you want!
Use this instead:
if ( a == b && a == c )