Search code examples
ctypescomparisonimplicit-conversion

Why does C compare 3 as equal to 3.0?


The problem is I can't understand how computer understood that 3 and 3.0 are the same in the very first place.

I think INT would get implicitly converted to FLOAT?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a=3;
    float b=3.0;
    if(a==b)
        printf("s");
    else
        printf("w");
    return 0;
}

I'm expecting the output of the code to be w, but the actual output is s. why? and please explain to me the perspective of the computer.


Solution

  • In the case of numbers, anyway, the equality operator == does not mean "Are these two things identical in every way?" What it means is, "Do these two things have the same value?"

    The integer 3 and the floating-point number 3.0 clearly have the same value, so if(3 == 3.0) is true.

    Similarly, on an ASCII machine, the value of the 'A' character is 65, so if('A' == 65) is true, even though the letter A and the number 65 might look like very different things at first.