Difference Between if and switch in C++

This post explain some points about switch-case statement and difference between if and switch-case.

Some Important Notes about Switch Case :

1) A switch statement can only work for equality comparisons.

2) Two case labels in a same switch cannot have identical values, But two 
   case labels can have same identical values in a nested switch (One case 
   label is of inner switch, and the other label is of outer switch).

3) Switch statements, which use character constants, are automatically 
   converted to integers i.e. their equivalent ASCII codes.

4) A switch statement can have upto 257 case statements as per 
   regulation of ANSI standard.

5) Fall Through Condition - It is a situation which is produced in absence
   of break statement. If there is no break statement in all the cases of 
   a switch statement, then it is called Fall Through.

Difference Between if and switch in C++

Basis If Switch
Test Expression Relational or Logical Equality
Number of Expressions/Variables If tests a series of expressions that may involve unrelated variables and complex expressions. Switch tests the value of same variable or equality expression against a set of constants.
Versatility If is more versatile, as it can handle ranges easily Switch case label must be a single value. It cannot handle ranges as like if statement.
Handling of Floating Point Numbers Can handle easily Cannot handle, because the case label value must be an integer
     

Incoming search terms:

  • difference between if and switch in c

Leave a Reply