Pitfalls in C Selection Statements


A Pitfall is when the program compiles without error but gives incorrect results. This is really bad and the cause of such famous disasters as the AT&T collapse of 1990.  In the examples below, red means danger, don't do this.

Pitfall #1

int p = 100;
int q = 50;
int result;
result = (p > 90) + (q < 90);

What value will be assigned the variable result?
What meaning does the value have?

Cause: C doesn't have a boolean data type, which would prohibit using an arithmetic operator on a logical expression.  Instead, C represents logical values as integers, and thus arithmetic is allowed by the compiler, even though it makes no sense in the real world.  The programmer in the above example probably meant to use the logical OR operator (||)  but made a mistake. Unfortunately the C compiler provides no assistance in identifying this error.   Languages with a built-in boolean type don't have this pitfall.

Pitfall #2

if (0 <= x <= 4)
{
    printf("Yes!");
}
else

   
printf("No.");
}

Will always print "Yes!"  for any value of x.  The correct syntax to use is:

if (0 <= x && x <= 4)

Pitfall #3

if (x = 10)
{
    printf("Yes!");
}

Will always print "Yes!"  for any value of x because it uses the assignment operator, not the equality operator.  The correct syntax to use is:

if ( x == 10 )
{
    printf("Yes!");
}

Pitfall #4

if (x > 0)
     sum = sum + x;
     printf("Greater than zero");
printf("Mice love cheese");


Will always print "Greater than zero"  for any value of x because the printf statement is not part of the if statement because the braces are missing despite the fact of indentation.

if (x > 0)
{
     sum = sum + x;
     printf("Greater than zero");
}
printf("Mice love cheese");

ALWAYS use braces, even though the compiler may not require them.

Pitfall #5

if (x > 0);
{
    printf("Greater than zero");
}

Will always print "Greater than zero"  for any value of x because the semicolon at the end of the if statement ended the statement.