Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

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

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

char c[20] = "hello";
foo(+c);
foo(+"hello");
question from:https://stackoverflow.com/questions/25701381/what-is-the-purpose-of-unary-plus-operator-on-char-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...