-3
#include <stdio.h>

int main()
{
    int x=3;
    float y=3.0;
    if(x==y)
        printf("\n x and y are equal");
    else
        printf("\n x and y are not equal")

    return 0;
}

The code prints "x and y are equal". Please explain how did this happen.

  • 4
    What did you expect to happen, and why? – dbush Aug 06 '20 at 15:52
  • Did you read https://floating-point-gui.de/ ? Did you refer to [this C reference](https://en.cppreference.com/w/c) ? Did you read the [C11 standard](https://web.cs.dal.ca/~vlado/pl/C_Standard_2011-n1570.pdf) ? Did you read [*Modern C*](https://modernc.gforge.inria.fr/) ? – Basile Starynkevitch Aug 06 '20 at 15:53
  • 2
    It is best described in the [C standard - 6.5.9 Equality operators](http://port70.net/~nsz/c/c11/n1570.html#6.5.9) . Really, any (full) answer will be just a bunch of citations from there – Eugene Sh. Aug 06 '20 at 15:54
  • The working are **as if** both `x` and `y` values are converted to `double`. The converted values are compared (perhaps bit-by-bit) and are found to be equal because `3.0f` converted to `double` has the same representation as `3` converted to `double` – pmg Aug 06 '20 at 15:57
  • your `int` will be type-converted to `float` (EDIT or `double`, I'm not 100% sure) automatically so that the left hand side and right hand side of the operator matches in type and then 3.0f and 3.0f will be compared and found to be equal – Louis Cloete Aug 06 '20 at 15:57
  • 3
    Does this answer your question? [checking for equality between an int and float in C](https://stackoverflow.com/questions/24067499/checking-for-equality-between-an-int-and-float-in-c) – Rohan Bari Aug 06 '20 at 15:58
  • 1
    It's called "Implicit Type Conversion." https://www.geeksforgeeks.org/type-conversion-c/ – Robert Harvey Aug 06 '20 at 15:58
  • 1
    If you are trying to recreate an example about "broken floating point math", the value of choice is typically `0.3`, not `3.0`. – StoryTeller - Unslander Monica Aug 06 '20 at 15:59

1 Answers1

5

When comparing an int variable to a float variable using ==, the int is converted to a float implicitly first, and then the comparison is made.

Hence, float(x) == y means 3.0f == 3.0f, which is true, that's why you it executes:

printf("\n x and y are equal");
BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31
  • 2
    Although it is correct that the `int` is converted to `float`, "float is larger than int" is not really the right way to describe the reason for that. Interpreted as a statement about the size in bytes of the two types, it is downright false for many C implementations. Rather, this is covered by the "usual arithmetic conversions", which specify it for the case in question directly, not as an application of a general rule based on any variation on size. – John Bollinger Aug 06 '20 at 16:11
  • @JohnBollinger Thanks for the catch, the comment on size variation was added as an edit by another user to my original answer. – BusyProgrammer Aug 06 '20 at 17:36