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

Time:11-11

In C programming we write conditional statements like switch, if etc... But for switch we can't write floating point numbers while giving condition. Why so what is the exact reason?

CodePudding user response:

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, and 0.1f 0.2f is not the same as 0.3f.

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.

CodePudding user response:

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