anime
anime

Reputation: 118

Why should be there the involvement of type promotion in this code?

In the code below the sizeof(int) will produce a signed int with a value of 4 bytes (suppose on a particular compiler) and -1 is also signed int, then my answer should be Yes but it displays No.

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

Upvotes: 1

Views: 133

Answers (1)

user2736738
user2736738

Reputation: 30926

Well it is the famous signed unsigned comparison. Here -1 which is signed number when compared to unsigned numbers - promoted to an unsigned number resulting in a big magnitude value (SIZE_MAX). So it is always false.

The explanation why there would be type promotion here when comparing:

From standard §6.3.1.8

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.

Also from §6.5.8 under relational operators

If both of the operands have arithmetic type, the usual arithmetic conversions are performed.

And what sizeof returns?

Under The sizeof and _Alignof operators §6.5.3.4

The value of the result of both operators is implementation-defined, and its type (an unsigned integer type) is size_t, defined in (and other headers).

And in section §7.19 under Common definitions

size_t which is the unsigned integer type of the result of the sizeof operator;

To clarify a bit further when you are converting -1 to size_t it will have the value (Basically modulo SIZE_MAX+1)

SIZE_MAX+1+(-1)

Also from standard §6.2.5 (Explaining the conversion)

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

Upvotes: 6

Related Questions