Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of unary plus operator on char array?

Tags:

c++

What does the following do? I thought + was for integer promotion only.

char c[20] = "hello"; foo(+c); foo(+"hello"); 
like image 878
user4014723 Avatar asked Sep 06 '14 14:09

user4014723


People also ask

What is the use of unary plus operator?

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.

What is the use of unary plus 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.


1 Answers

It forces the array to decay to a pointer, as indirectly stated in §5.3.1 [expr.unary.op]/7:

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.

You might not see it at first, but since an array is not one of the types listed, it must be converted to a pointer in order to fit. From there, the value of the pointer is returned.

In both cases, a foo(const char *) would be chosen over a foo(const char(&)[N]). For some examples of useful things you can use unary plus for, see this answer. Included are converting an enum type to an integer and getting around a linking issue. As you say, it can also be used for integral promotion. For example, unsigned char byte = getByte(); std::cout << +byte; will print the numerical value and never the character.


A straightforward example is:

char a[42]; cout << sizeof(a) << endl;  // prints 42 cout << sizeof(+a) << endl; // prints 4 
like image 107
chris Avatar answered Oct 09 '22 09:10

chris