Floating number in switch case : MCQ



This tutorial will explain you another verity of switch case statement. What will happen if we use floating number in switch case statement ?

Floating number in switch case : MCQ

void main()
{
 float choice = 10.1 ;
 switch(choice)
  {
  case 10.1 :
            printf("\nCase 10.1");
            break;
  case 10.2 :
            printf("nCase 10.2");
            break;
  case 10.3 :
            printf("nCase 10.3");
            break;
  }
}

Options : Do you think program will compile ?

  1. Yes
  2. No

Explanation

First of all, each and every compile have its own precision defined. If we compare the two numbers without precision then it will always return true if two numbers are same

Consider the below program -

int num = 10;
if(num == 10) {
  printf("True");
}

It works in case of integer value, if we use floating point number then compiler have different representation format of constant value and floating point variable.

float num = 10.20;
if(num == 10.20) {
  printf("True");
} else {
  printf("False");
}

Above program always ends in false condition because compiler have two representations of float number. so actual comparison will be like this –

if(10.19999999999 == 10.20)

Same situation is happening when we use floating number in Switch case. so it is re-commanded to use constant integer expression in the switch case statement,

Recommended Tutorial : Rules of using switch case