C if-else mistake



We have already studied the if-else statement in c programming. In this chapter we will be learning common if-else mistake committed by novice programmers.

C Programming if-else mistake

If-else mistake 1 : Assignment operator and comparison operators

Basic if-else mistake committed by the novice user is use of assignment operator in if statement instead of the comparison operator.

Assignment operator = is used for assigning value to variable while comparison operator == checks whether LHS and RHS entries are same or not

if(var = 10)
{
   //Statement 1
   //Statement 2
   //Statement 3
   //Statement n
}

Consider above program, if we use assignment operator in if statement then value 10 will be assigned to variable var. Any non-zero number inside if condition is considered as true condition so it will always executes to true

if(var = 0)
{
   //Statement 1
   //Statement 2
   //Statement 3
   //Statement n
}

however above statement executes to be false as we are assigning 0 to variable. Best practice of using if statement is –

if(var == 10)
{
   //Statement 1
   //Statement 2
   //Statement 3
   //Statement n
}

In if statement use == instead of =

If-else mistake 2 : Use of Semicolon

In C Programming, we use semicolon as termination character. Same case is applicable for if statement. Semicolon after the if statement will terminate if statement

Consider the below program –

if(var == 10);
{
   //Statement 1
   //Statement 2
   //Statement 3
   //Statement n
}

above program would execute statement 1..4 without any issue because semicolon at the end of if statement makes if-statement bodyless. Compiler will expand above program as –

if(var == 10) {
}
{
   //Statement 1
   //Statement 2
   //Statement 3
   //Statement n
}

Use of semicolon after if statement does not throw compile error. It will execute if statement without any issue.

If-else mistake 3 : Else without using if

Using the else statement without if will throw compile error because each time if and else must come in pair with else as optional part.

Statement1 ;
Statement2 ;
..
   else
     {
     Statement 3;
     Statement 4;
     .
     .
     }
}

compiler will throw an error message – Misplaced Else. Important rule of thumb is that each else must have corresponding if

If-else mistake 4 : Opening and Closing Braces

Statement1 ;
  if(condition)
Statement1 ;
Statement2 ;

else
{
Statement 3;
Statement 4;
}

Explanation :

  1. If multiple Statements within if must be wrapped in Pair of braces.
  2. Error Message : Misplaced else
  3. Statement1 and statement2 must be wrapped inside if
  4. Here only Statement1 is the part of if
if(condition)
     {
     Statement1 ;
     Statement2 ;
     }
   else
     {
     Statement 3;
     Statement 4;
     }