Dave Black
Dave Black

Reputation: 65

Why does this code return as false in C

Ok, trying to understand why the if statement below is false. I've turned it inside out and can't understand what is going on here.

#define SIZE (sizeof(arr)/sizeof(int))

int main(int argc, char** argv)
{
    int arr[] = {1,2,3,4,5,6,7,8};

    if ( -1 <= SIZE )
        printf( "true" );
    else
        printf( "false" );

    return 0;

}

Upvotes: 1

Views: 138

Answers (1)

unwind
unwind

Reputation: 399843

It prints false because of signed/unsigned mismatch in the comparison.

The result of sizeof is a size_t value, which is unsigned. When the int value -1 is compared to that, the integer is interpreteted as a very large unsigned value.

The C99 draft standard expresses this like so:

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

Here, the size_t is at least unsigned int which makes it rank equal to or out-rank int, and thus cause the int to be converted to size_t.

Also, main() really does return int, I don't understand why you edited that out.

Upvotes: 12

Related Questions