Was the unary +
operator only included for symmetry with the unary -
operator, or does it find some practical use in C++ code?
Searching here, I came across What is the purpose of the unary '+' operator in C?, but the only useful scenarios there involve preprocessor macros. Those are good to know, but they seem to be some less common situations, and involve macros. Are there any use cases involving more common C++ code?
The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean. The increment/decrement operators can be applied before (prefix) or after (postfix) the operand.
Unary - changes the sign of a numeric expression to the right of the operator. Unary + has no effect on an expression; it is included for completeness and because some programmers like to use it to emphasize that a number is positive.
In computer programming, a unary operator is an operator that takes only one value for its operation. This operation required two values (x and 1) and is an example of a binary operation.
Unary operator in C++ It operates on a pointer variable and returns an l-value equivalent to the value at the pointer address. This is called "dereferencing" the pointer. The unary address-of operator (&) takes the address of its operand.
char ch = 'a'; std::cout << ch << '\n'; std::cout << +ch << '\n';
The first insertion writes the character a
to cout
. The second insertion writes the numeric value of ch
to cout
. But that's a bit obscure; it relies on the compiler applying integral promotions for the +
operator.
Symmetry with unary -
isn't entirely useless; it can be used for emphasis:
const int foo = -1; const int bar = +1;
And an overloaded unary +
can be used to denote an operation that yields the same logical value as its operand, while performing some non-trivial computation. (I've seen this done for type conversions in Ada, which permits unary +
, but not conversions, to be overloaded.) I don't have a good C++ example to hand, and one could argue that it would be poor style. (Then again, I've seen plenty of rants about overloading <<
.)
As for why C++ has it, it's probably largely for consistency with C, which added it with the 1989 ANSI standard. The C Rationale just says:
Unary plus was adopted by the C89 Committee from several implementations, for symmetry with unary minus.
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