Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 752
zneak Avatar asked Jul 09 '11 19:07

zneak


People also ask

What is the use of unary plus operator in C?

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.

What is the point of unary plus?

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.

What are unary operators in C programming?

Unary operators: are operators that act upon a single operand to produce a new value. Types of unary operators: unary minus(-) increment(++) decrement(- -)


2 Answers

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.

like image 155
Nemo Avatar answered Sep 22 '22 20:09

Nemo


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..

like image 35
lccarrasco Avatar answered Sep 22 '22 20:09

lccarrasco