Common mistakes with conditionalss
Comments and questions to John Rowe.
Using = not ==
|
| Wrong
| Right
|
if ( a = b )
|
|
| The expression on the left set a to equal b, the
one on the right tests to see if a equals b.
|
Using a == b == c or a >b > c
|
| Wrong
| Right
|
if (a == b == c)
|
|
if ( a > b > c )
|
|
|
|
| Wrong
| Right
|
|
|
|
|
| Rounding errors mean that two floating-point expressions
are unlikely to be equal even when mathematically they ought to be. Instead
we use fabs() of the difference. Note fabs()
not abs() which is the integer function.
|
| Wrong
| Right
|
|
|
Using abs() not fabs()
Remember that abs() is the integer
so any floating-point expression whose absolute
value is less than one will become zero.
|
|
// (This is the same as the previous example.)
|
Longer example of comparing floating-point numbers for equality
|
Log in