lundi 30 novembre 2020

Why does this if condition not work when I add parentheses around the left hand side of the inequation?

I was trying out a problem, and my code failed one of its test cases. I traced back the error, and it can be summarized by the following code:

#include <stdio.h>

int main(void)
{
  int a = 90000;
  int b = 80000;

  if (a * b <= a + b)
  {
    printf("YES\n");
  }
  else
  {
    printf("NO\n");
  }
}

I would expect the output to be a "NO" (since 90000 * 80000 > 90000 + 80000). But turns out, when compiled and run, the above program outputs "YES".

I suspect this has something to do with the range of an int in C. The range of an int on a 64-bit OS (the one I have) is 4 bytes, thus all the integers from -2,147,483,648 to 2,147,483,647 can be represented by an int. But a * b in the above code is 7200000000, which is well beyond the bounds of an int. So I tried casting the value of a * b to a long long int as follows

#include <stdio.h>

int main(void)
{
  int a = 90000;
  int b = 80000;

  if ((long long int) a * b <= a + b)
  {
    printf("YES\n");
  }
  else
  {
    printf("NO\n");
  }
}

But still the output stays the same, "YES". I can't seem to figure out how I can make the program return the correct output. How can I do it? This has been solved. The above code works perfectly fine.


Like MathewHD pointer out in the comments that declaring a and b as longs rather than ints solves the issue. Then why does casting not work? Casting works (refer the above code). Also, where is this temporary variable having the value of a * b stored, and how can I change the data type of that temporary variable?


Turns out I was using a slightly different code when the error was generated. Using the above code (the one which includes casting to a long), does give the expected output, however adding parentheses around the left hand side of the condition, makes the program return the wrong output i.e. "YES". The code follows

#include <stdio.h>

int main(void)
{
  int a = 90000;
  int b = 80000;

  if ((long long int) (a * b) <= a + b)
  {
    printf("YES\n");
  }
  else
  {
    printf("NO\n");
  }
}

The main reason why I initially thought of adding the parentheses around the left hand side of the inequation, was to ensure that the compiler does not misinterpret the casting to be for only one of the involved integers rather than their product. So I just wanted their product to be casted. I would love an explanation as to why adding the parentheses does more harm than good, i.e. why doe it make the program return wrong outputs?

One of my previous question also remains: Where is this temporary variable having the value of a * b stored, and how can I change the data type of that temporary variable?

Aucun commentaire:

Enregistrer un commentaire