-1

In below program, i didnt understand how float and int value are same.

int main()
{
    int a=3;
    float b=3.0;
    if(a==b)
    {
        printf("A is equal to b");
    }
    else{
        printf("A is not euql to b");
    }
}

The output of the program is "A is equal to b"

yvesmancera
  • 2,915
  • 5
  • 24
  • 33
Manish
  • 55
  • 1
  • 7
  • 1
    There are no heterogeneous comparisons. In the expression `a == b`, the operands are first *converted* to a common type. – Kerrek SB Sep 08 '15 at 16:53
  • 2
    What is the problem? The `int` is converted to `float` and compared to `b`. For the value 3, it happens that the converted value matches 3.0. – Bo Persson Sep 08 '15 at 16:53
  • Also see: http://stackoverflow.com/questions/1161199/is-relational-comparison-between-int-and-float-directly-possible-in-c – sshashank124 Sep 08 '15 at 17:08

2 Answers2

3

if(a==b) does not compare types, it compares values.


As @Kerrek SB commented, the value(s) are converted to a common type.

Each a and b go though "usual arithmetic conversions" before the comparison.

... the values yielded by operators with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type. The use of evaluation formats is characterized by the implementation-defined value of FLT_EVAL_METHOD: C11dr §5.2.4.2.2 9

Conversion to floating point is to float, double or long double depending on FLT_EVAL_METHOD.

Assuming conversion to float...:

Otherwise, if the corresponding real type of either operand is float, the other operand is converted, without change of type domain, to a type whose corresponding real type is float. §6.3.1.8 1

So a converts to a float with the value of 3.0 before the comparison.

Since the values compare the same, they pass the if(a==b).


Note: Conversion can cause issues as not all int may covert exactly to a float.

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
1

Actually the int value will be typecasted to float and then the if condition is evaluated.

Sujit Prasad
  • 117
  • 6