-2
int main()
{
  if (sizeof(int) > -1)
    printf("Yes");
  else
    printf("No");
}

Output should be Yes, but the output is No. what is the logic being used?

kiner_shah
  • 3,939
  • 7
  • 23
  • 37

2 Answers2

1

For your question, you need to understand how the type conversion is done. C specifies:

  • If either operand is of type long double, the other shall be converted to long double.
  • Otherwise, if either operand is double, the other shall be converted to double.
  • Otherwise, if either operand is float, the other shall be converted to float.
  • Otherwise, if either operand is unsigned, the other shall be converted to unsigned.

So what happens is that the sizeof(int) operator returns an unsigned value which is being compared to signed value. Hence, -1 will be converted to an unsigned integer which in turn returns the answer No.

So as @user3386109 has pointed out, you can add (__int128_t) before -1. You can also write (__int128) with t omitted.

So your final code will be:

int main()
{
  if (sizeof(int) >  (__int128) -1)
    printf("Yes");
  else
    printf("No");
}

which gives the answer yes.

Arnav
  • 163
  • 1
  • 8
0

sizeof() returns a value of type size_t, which is an alias of an implementation-defined unsigned integral type.

Therefore, the other term is converted into unsigned type also!

So -1 becomes SIZE_MAX, and hence the test becomes if (sizeof(int) > SIZE_MAX) hence, the output you get - not what you expect.

This is explained further in Signed/unsigned comparisons

Andrew
  • 2,046
  • 1
  • 24
  • 37