Does Unary + operator do type conversions?

后端 未结 4 619
眼角桃花
眼角桃花 2021-01-04 04:28

Till now I was believing that there is no use of unary + operator.

But then I came across with following example:

char ch;
short sh;
in         


        
4条回答
  •  醉梦人生
    2021-01-04 05:26

    Unary + performs integer promotions on its operand, we can see this by going to the draft C99 standard section 6.5.3.3 Unary arithmetic operators which says (emphasis mine going forward):

    The result of the unary + operator is the value of its (promoted) operand. The integer promotions are performed on the operand, and the result has the promoted type.

    and section 6.3.1 Arithmetic operands says:

    If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.48) All other types are unchanged by the integer promotions.

    Note that all other types are unchanged by the integer promotions and thereofore double stays a double. This would also hold for float as well, which would not be promoted to double.

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

提交回复
热议问题