What does the unary plus operator do? There are several definitions that I have found (here and here) but I still have no idea what it would be used for. It seems like it doesn't do anything but there has be a reason for it, right?
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. Integral promotion is performed on integral operands. The resultant type is the type to which the operand is promoted.
In mathematics, an unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands. An example is any function f : A → A, where A is a set. The function f is a unary operation on A.
Addition. The + operator in Python can be utilized in a unary form. The unary structure implies character, restoring the same value as its operand.
Unary plus ( + ) or minus ( - ) converts a non-numeric value into a number. The unary minus negates the value after the conversion. The prefix increment operator adds one to a value. The value is changed before the statement is evaluted. The postfix increment operator adds one to a value.
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. :-)
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