What is the purpose of the unary plus (+) operator in C?

前端 未结 8 2101
攒了一身酷
攒了一身酷 2020-11-28 05:58

In C, it\'s legal to write something like:

int foo = +4;

However, as far as I can tell, the unary plus (+) in +4

8条回答
  •  星月不相逢
    2020-11-28 06:28

    Not precisely a no-op

    The unary + operator does only one thing: it applies the integer promotions. Since those would occur anyway if the operand were used in an expression, one imagines that unary + is in C simply for symmetry with unary -.

    It's difficult to see this in action because the promotions are so generally applied.

    I came up with this:

    printf("%zd\n", sizeof( (char) 'x'));
    printf("%zd\n", sizeof(+(char) 'x'));
    

    which (on my Mac) prints

    1
    4
    

提交回复
热议问题