Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unary plus (+) against literal string

Today I wrote an expression:

"<" + message_id + "@" +  + ">"
                          ^
                          |
                          \____  see that extra '+' here!

and got surprised that it actually compiled. (PS message_id is a QString, it would also work with an std::string)

I often do things like that, leave out a variable as I'm working and I expect the compiler to tell me where I'm still missing entries. The final would look something like this:

"<" + message_id + "@" + network_domain + ">"

Now I'd like to know why the + unary operator is valid against a string literal!?

like image 755
Alexis Wilke Avatar asked Dec 07 '13 08:12

Alexis Wilke


People also ask

What's the point of unary plus?

The unary plus operator ( + ) precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.

Is the ++ operator unary?

Unary Increment (++) In this type, the Unary Operator is denoted by the '++' sign. It increases the value by 1 to the operand and then stores the value to the variable. It works for both Prefix and Postfix positions.

What is unary plus and unary minus?

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 evaluated. The postfix increment operator adds one to a value.

What does unary plus do in C++?

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.


1 Answers

Unary + can be applied to arithmetic type values, unscoped enumeration values and pointer values because ...

the C++ standard defines it that way, in C++11 §5.3.1/7.

In this case the string literal, which is of type array of char const, decays to pointer to char const.

It's always a good idea to look at the documentation when one wonders about the functionality of something.


“The operand of the unary + operator shall have arithmetic, unscoped enumeration, or pointer type and the result is the value of the argument. Integral promotion is performed on integral or enumeration operands. The type of the result is the type of the promoted operand.”

like image 114
Cheers and hth. - Alf Avatar answered Sep 21 '22 18:09

Cheers and hth. - Alf