In C, it's legal to write something like:
int foo = +4;
However, as far as I can tell, the unary plus (+
) in +4
is a no-op. Is it?
The result of the unary plus operator (+) is the value of its operand. The operand to the unary plus operator must be of an arithmetic type. The - (unary minus) operator negates the value of the operand. The operand can have any arithmetic type.
The + (unary plus) operator maintains the value of the operand. The operand can have any arithmetic type or pointer type. The result is not an lvalue. The result has the same type as the operand after integral promotion.
Unary operators: are operators that act upon a single operand to produce a new value. Types of unary operators: unary minus(-) increment(++) decrement(- -)
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.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With