-3

Please give the reason for the output...why it's giving 'bye' while the condition if statement is true because the size of int is 2 or 4 byte.

   #include<stdio.h>
        #include<conio.h>
        int main()
        {
        if(sizeof(int)>-1)
            printf("hi");
        else
            printf("bye");
        return 0;
        }

2 Answers2

2

See http://en.cppreference.com/w/c/language/sizeof

Both versions return a value of type size_t.

See size_t, http://en.cppreference.com/w/c/types/size_t
which states that it is unsigned.

If therefor the comparison is effectively with a high positive value,
then the logical expression is basically always false.

If you would help the compiler understand what you really want to do,
e.g. by changing to

((int)sizeof(int))>-1

things are different.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
2

It's because the return type of sizeof() is size_t and sizeof() never gives size in negative bytes.

sizeof(int) results is type of unsigned.

And here if(sizeof(int)>-1) Comparison is happening between different types i.e signed(-1) and unsigned. So internally compiler will do implicit typecasting i.e signed gets converted into unsigned and -1 equivalent unsigned value is all one's i.e 4294967295.

So now condition looks like if(4 > 4294967295) Which is false so it prints bye.

See this for sizeof() return type http://en.cppreference.com/w/c/types/size_t

Achal
  • 11,821
  • 2
  • 15
  • 37