Does Unary + operator perform type conversion?

So far, I have assumed that there is no unary + operator.

But then I came across the following example:

 char ch; short sh; int i; printf("%d %d %d",sizeof(ch),sizeof(sh),sizeof(i)); // output: 1 2 4 printf("%d %d %d",sizeof(+ch),sizeof(+sh),sizeof(i)); // output: 4 4 4 

Does this mean that + does type conversion here?

Because he behaves the same as

 printf("%d %d %d",sizeof((int)ch),sizeof((int)sh),sizeof(i)); // output: 4 4 4 

This makes me think that + is doing type conversion.

But then I try on double

 double f; printf("%d %d",sizeof(+f),sizeof((int)f),sizeof(f)); // output: 8 4 8 

This makes me rethink the unary + operator.

So, my second question is: does the unary operator + special effect in the sizeof operator?

+14
c sizeof integer-promotion
Jul 17 '14 at 13:56 on
source share
4 answers

Unary + performs integer axioms in its operand, we can see this by going to the draft standard section C99 6.5.3.3 Unary arithmetic operators that say (emphasis mine forward):

The result of a unary + operator is the value of its (advanced) operand. Entire promotions are performed in the operand , and the result is of an advanced type.

and section 6.3.1 Arithmetic operands say:

If int can represent all values ​​of the original type, this value is equally converted to int; otherwise, it is converted to unsigned int. They are called whole promotions . 48) All other types are unchanged with whole promotions.

Please note that all other types are not changed by whole promotions, and therefore double remains double. This will also be the case for a float, which will not rise to two.

Also note that using %d for the sizeof result is undefined behavior, as the result is size_t. the proper format specifier would be %zu .

+19
Jul 17 '14 at 14:12
source share

When smaller types participate in an expression with larger types (for example, char less than short , which is basically less than int , which may be less than long ), the involved types advance to larger tio.

So, when you use the unary + operator, you get int because int is a natural integer type in C.

As for the double type, the natural floating-point type for C is double , so there is no progress on values ​​or variables that already have a double type.

The sizeof operator has nothing to do with this.

+4
Jul 17 '14 at 2:00
source share

The unary + operator starts the "initial" ordinary arithmetic conversions, so all integer operands whose type has a lower rank than the rank of int and unsigned int are raised to int (or unsigned int if int does not apply to all values ​​of the type promoted by this implementation).

+4
Jul 17 '14 at 2:05
source share

This is not sizeof , this is unary + . Unary + operands undergo "ordinary arithmetic transformations." See, for example, this other answer , including the usual addition.

+2
Jul 17 '14 at 14:01
source share



All Articles