Why the usage of floating point numbers in switch condition doesn't work?

Viewed 295

As shown in the image, it is throwing the error. Please help me to find the answer.

switch case example

#include <stdio.h>
void main() {
 float a = 1.0;

 switch (a) {
    case 1:
     printf ("1");
     break;

    case 1.0:
     printf ("10");
     break;
    }
}
3 Answers

Because switch depends on exact, plain-data comparison.

Comparisons between floats probably don't work as you expect them to, for example, there's a negative and a positive zero.

See: Is floating point math broken?

For these reasons, you can't "simply" say "a == b" when you mean that, as a human. That's why the C standard simply doesn't allow it as a case in a switch.

Truth is: the fact that you're trying to do that is a good reason for forbidding it! Either you're using floats where you shouldn't (namely, to store a limited set of discrete values), or you haven't really understood how floats work, and using them in a switch statement will lead to unexpected behaviour.

As for the "Please help me" part of your question, you can probably implement that more-or-less as follows...

rather than

double x=1.,y=2.;
blah; blah; blah;
switch(x){
  default: break;
  case y: blah; break;
  }

try instead something like

double x=1., y=2., xmax=10000., xmin=1.;
int   ix=1, iy=2,  imax=100;
blah; blah; blah;
ix = ((x-xmin)/(xmax-xmin))*((double)imax);
iy = ((y-xmin)/(xmax-xmin))*((double)imax);
switch(ix){
  default: break;
  case iy: blah; break;
  }

why can't we use floating point numbers in switch conditional statements?

  1. Because the language definition says so.

  2. Because comparing floating-point numbers for exact equality (which a switch statement implicitly does) is often a bad idea.

  3. Because using floating-point variables as control variables is usually a bad idea. @Steve Summit

  4. No compelling need for this feature.

Related