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

前端 未结 8 2091
攒了一身酷
攒了一身酷 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:47

    There's one very handy use of the unary plus operator I know of: in macros. Suppose you want to do something like

    #if FOO > 0
    

    If FOO is undefined, the C language requires it be replaced by 0 in this case. But if FOO was defined with an empty definition, the above directive will result in an error. Instead you can use:

    #if FOO+0 > 0
    

    And now, the directive will be syntactically correct whether FOO is undefined, defined as blank, or defined as an integer value.

    Of course whether this will yield the desired semantics is a completely separate question, but in some useful cases it will.

    Edit: Note that you can even use this to distinguish the cases of FOO being defined as zero versus defined as blank, as in:

    #if 2*FOO+1 == 1
    /* FOO is 0 */
    #else
    /* FOO is blank */
    #endif
    

提交回复
热议问题