Saturday, July 13, 2013

Switch Statement with float in C

We know that Switch Statement takes only integer values for switching to cases. But what happens if we place a float value in the switch statement. Does it return a error or it executes successfully?

Consider the following example, to understand about this concept.

  1. #include<stdio.h>
  2. main()
  3. {
  4. float a=3.4;
  5. switch(a)
  6. {
  7. case 3 : printf("Hello 3");
  8.             break;
  9. case 4 : printf("Hello 4");
  10.             break;
  11. default : printf("It is some other value");
  12. }
  13. return 0;
  14. }
Check out what would be result of the program. It results in an Error. This is because of switch doesn't take a float value. Then how to make it take the value?

Just replace the line 5 with the following line,
switch((int)a)
This works well and the result is Hello 3. This is because, we have the concept of Type casting. Based on the Type casting, float value is converted into int and then the value is taken.

But this is not a good practice to take this, because a float with integral value 3 and whatever the decimal part may result in the same output. So this approach is not a good practice.