in Programming in C
721 views
2 votes
2 votes
output of the following program is 'no' but why.
 
#include <stdio.h>
int main()
{
    if (sizeof(int) > -1)
        printf("Yes");
    else
        printf("No");
    return 0;
}
in Programming in C
721 views

2 Comments

it will print "no"...sizeof return unsigned value.. -1 will be promoted to unsigned value of 2^32-1(assuming integer of 4 bytes)..
1
1
Comparison of a signed and unsigned number cannot happen

While comparing , the signed number -1 is converted to unsigned which generates a number that is very much bigger

This number will definetly be greater than size of (int) assuming it as 4

therefore prints "no" as the answer
–1
–1

2 Answers

1 vote
1 vote

Usual arithmetic conversions are implicitly performed for common type.If both operands are integers. In that case,
 1. if both operands  have the same signedness (both signed or both unsigned),then nothing convension performed.
 2. if the signedness is different: then unsigned operand converted implicitly into signed type operand.(56u+45; 56u is unsigned and 45 is signed  so, 45 is converted to unsigned)
For more Implict Conversion u may read -http://en.cppreference.com/w/c/language/conversion

When When we comparing a signed integer with an unsigned integer
      if (unsignedint > signedint)
then unsigned operand converted implicitly into signed type operand
        
sizeof(int) returns size_t which is as unsigned int(Size of unsigned int data type is 4) .constant value -1 is signed int.
When When we comparing a signed integer -1 with an unsigned integer 4.
    if (sizeof(int) > -1)
then signed integer value -1 implicitly converted into unsigned integer value 4294967295.
So expression becomes-
if(sizeof(int) > -1 ) ==> if(4 >4294967295)
 So condition false and else part Printf function excute and print "FALSE"

You can explicit cast it to if((signed)sizeof(int)>-1) to return true.

0 votes
0 votes
Here sizeof(int) is 4 which is unsigned. While -1 is signed.

C does not allow comparing signed with unsigned. So it convert signed number (i.e. -1) into unsigned number , which becomes too big than 4 .

Thats why  output is No.

Related questions