Skip to content
Physics and Astronomy
Home Our Teaching Resources C programming Common mistakes
Back to top
On this page
Contents

Common mistakes with conditionalss

Using the wrong expression

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 )
 

Not using else

Wrong Right
 
 

Comparing floating-point numbers for equality

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
                                                                                                                                                                                                                                                                       

Validate   Link-check © Copyright & disclaimer Privacy & cookies Share
Back to top