Monday, December 14, 2009

Why switch expression does not work with float types?

Have you people ever thought of why switch statement does not work with float/double types?
I have read in text books about the constraints of switch statements but i have never thought(infact i didnt take pain to find it out :P) why switch cant be used with floating point values,
but today one of my friend asked me about it(she is doing civil engg)as she has a viva tomorrow on c programming.I was not able to answer her immediately,i searched a lot and i found some answers.I would like to share it with everybody.
The reason is...
consider an example
float b = 2.51F;

switch(b)
{
case 2.51F:
Console.WriteLine("A");
break;
default:
break;
}
Because floating points tend do be less accurate than integers and might
shift a little dependin on the used processor it runs on and the generated
assembler code. floats are not a accurate number.In theory you assign 2.51000000..... and compare with 2.51000000.....
according to the example, but in reality the internal saved registery
number might be ranging between 2.50999998..... 2.51000011..... depending on
the generated code of the compiler.

This is because
2.51F may not equal 2.51F at any given time
one of them may be 2.51000000000001

If you want this then you need to decide on the level of precision you
want and treat it as an integer

something like this should work
switch( (int)(b*100) )
{
case 251:
}

Infact that the float type can not represent exact values (which is really what you need for a switch
statement).

2 comments:

Shabana said...

Thanx for the gr8 info dear.... I never knew abt it.... Keep giving us such kind of useful info....

Like Rain in the Forest said...

Its a very informative entry.Though being a non computer science student, you have made your point clear and concise. continue your efforts.. :)

Post a Comment