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

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


You can use it as a sort of assertion that an expression has arithmetic type:

#define CHECK_ARITHMETIC(x) (+(x))

This will generate a compile-time error if x evaluates to (say) a pointer.

That is about the only practical use I can think of.


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


As per the C90 standard in 6.3.3.3:

The result of the unary + operator is the value of its operand. The integral promotion is performed on the operand. and the result has the promoted type.

and

The operand of the unary + or - operator shall have arithmetic type..