-4

I have attached two programs. I got the programs from a web portal. Could you tell the explanation for the same?

Program 1:

#include<stdio.h>

int main()
{
    float x = 0.4;
    if (x == 0.4)
        printf("\n if");
    printf("\n sizeof(0.4) : %d sizeof(x) : %d",sizeof(0.4) , sizeof(x));
    return 0;
}

Program 2:

#include<stdio.h>

int main()
{
    float x = 0.5;

    if (x == 0.5)
        printf("\n if") ;
    printf("\n sizeof(0.5) : %d sizeof(x) : %d",sizeof(0.5) , sizeof(x));
    return 0;
}

For Program 1, I got the output as:

sizeof(0.4) : 8 sizeof(x) :4

For Program 2, I got the output as:

if
sizeof(0.5) : 8 sizeof(x) :4

What is the difference between these two programs executions?

This is not a duplicate of the old posted question....

I need the explanation why if is condition got passed for the value of xin multiples of 5

chand
  • 1
  • 2

1 Answers1

0
if(x == 0.4) // here you are comparing float values with double
 printf("\n if") ;

so in this case implicit type casting will occur internally, at that time float value will converted in to double.(while converting float value into double it will put 0 for lower 32 bits. so condition fails)

if(x == 0.4f)
 printf("\n if") ; // now it will print if

Normally When you give sizeof(0.4), it will treat 0.4 as double. for float give sizeof(0.4f), Now it will give output sizeof(0.4): 4

Sathish
  • 3,740
  • 1
  • 17
  • 28