What does the unary plus operator do?
Actually, unary plus does do something - even in C. It performs the usual arithmetic conversions on the operand and returns a new value, which can be an integer of greater width. If the original value was an unsigned integer of lesser width than int
, it will be changed to a signed
value as well.
Usually this isn't that important, but it can have an effect, so it's not a good idea to use unary plus as a sort of "comment" denoting that an integer is positive. Consider the following C++ program:
void foo(unsigned short x)
{
std::cout << "x is an unsigned short" << std::endl;
}
void foo(int x)
{
std::cout << "x is an int" << std::endl;
}
int main()
{
unsigned short x = 5;
foo(+x);
}
This will display "x is an int".
So in this example unary plus created a new value with a different type and signedness.
It's there to be overloaded if you feel the need; for all predefined types it's essentially a no-op.
The practical uses of a no-op unary arithmetic operator are pretty limited, and tend to relate to the consequences of using a value in an arithmetic expression, rather than the operator itself. For example, it can be used to force widening from smaller integral types to int
, or ensure that an expression's result is treated as an rvalue and therefore not compatible with a non-const
reference parameter. I submit, however, that these uses are better suited to code golf than readability. :-)
From K&R second edition:
The unary + is new with the ANSI standard. It was added for symmetry with the unary -.
I've seen it used for clarity, to emphasize the positive value as distinct from a negative value:
shift(+1);
shift(-1);
But that's a pretty weak use. The answer is definitely overloading.
One thing the built-in unary +
does is turning lvalue into an rvalue. For example, you can do this
int x;
&x;
but you can't do this
&+x;
:)
P.S. "Overloading" is definitely not the right answer. Unary +
was inherited from C and there's no user-level operator overloading in C.