722 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;
}

2 Answers

1 votes
1 votes

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

2 votes
2 votes
0 answers
1
0 votes
0 votes
1 answer
4
Roy12 asked Jun 7, 2022
467 views
I want to understand why the statement “I am lying” is a liars paradox as I unable to to toggle between the truth values for this statement. Thanks in advance.