Sunday, 11 January 2015

Comparison of a float with another value in C

Comparison of a float with another value in C:

Find out the output of the below program
#include <iostream>
using namespace std;
int main (int nNumberofArgs, char* pszArgs[])
{
    float fVal = 1.2;
    if (fVal == 1.2)
        printf("I am in the IF condition");
    else if (fVal == 1.2f)
        printf("I am in the ELSE IF condition");
    else
       printf("iam in the ELSE condition");
  return 0;
}




The output of above program is
I am in the ELSE IF condition

The explanation about the output is  fVal == 1.2, that returns false and expression fVal == 1.2f” returns true.

Let us see the below sample and let us understand the output
#include <iostream>
using namespace std;
int main (int nNumberofArgs, char* pszArgs[])
{
   float fVal = 1.2;
   printf("%d %d %d", sizeof(fVal), sizeof(1.2), sizeof(1.2f));
   return 0;
}
The result is
4 8 4

Unpredictable, It prints size of float, size of double and size of float.

If we do not specified ‘f’ at the end of the value the compiler consider that as the double so the sizeof (1.2) is 8.

So the expression fVal==1.2 has a double on right side and float which are stored in a single precision floating point format on left side. In such situations float is promoted to double.

The double precision format uses more bits for precision than single precision format.
Note that the promotion of float to double can only cause mismatch when a value uses more precision bits than the bits of single precision.

Let us see the another example and watch the result
#include <iostream>

using namespace std;
int main (int nNumberofArgs, char* pszArgs[])
{
    float fVal = 1.5;
    if (fVal == 1.5)
        printf("I am in the IF condition");
    else if (fVal == 1.5f)
        printf("I am in the ELSE IF condition");
    else
        printf("iam in the ELSE condition");
  return 0;
}

Output of the above program is :
I am in the IF condition


1 comment:

samba said...

Thank you very much for the post.but still i am not clear why it is going to the "I am in the IF condition " when we use only 1.5 !! could you explain that please.