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 )
  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 && b == c )

if ( a > b > c )
  if ( a > b && b > c )

Not using else

Wrong Right

  if ( x > 100 ) 
    printf("x is greater than 100\n");
  if ( x > 10 )
    printf("x is greater than 10 but less then or equal to 100\n");
  if ( x > 0 )
    printf("x is greater than 0 but less then or equal to 10\n");
  else 
    printf("x is zero or negative\n");
Step through this code


  if ( a != b) {
    c = c/(a-b);
  }


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
  if ( x*x == 2.0 )           // Wrong!

  if (fabs(x*x - 2.0) < 1e-6)  // 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.
  if (abs(x*x - 2.0) < 1e-6)
    printf("Should have used fabs()!\n");

  if (fabs(x*x - 2.0) < 1e-6)  // Right

// (This is the same as the previous example.)

Longer example of comparing floating-point numbers for equality

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
  double x;

  x = sqrt(2.0);

  if ( x*x == 2.0 )           // Wrong!
    printf("x*x is exactly 2\n");
  else
    printf("x*x - 2 is %g\n", x*x - 2.0);

  if (fabs(x*x - 2.0) < 1e-6)  // Right
    printf("Close enough!\n");

  // Now let's see what happens when we use abs() by mistake
  x = x + 0.1;
  if (abs(x*x - 2.0) < 1e-6)
    printf("Should have used fabs()!\n");

  return 0;
}
Step through this code


                                                                                                                                                                                                                                                                       

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