Reputation: 14448
I know that C & C++ both are different languages, today I make a little typo in the following program but the program compiles fine on various C++ compilers (g++,clang,MSVC++)
Consider following program:
int main()
{
int s[]={3,6,9,12,18};
int* p=+s; // Observe this strange looking initialization due to use of unary + operator
}
The above program compiles fine in C++ (See live demo here) but not in C (See live demo here.) My compiler ( gcc 4.8.1 ) gives me following error when I compile it as a C program.
[Error] wrong type argument to unary plus
What purpose the unary plus operator serves here? What it does exactly here? Why it is not allowed in C?
Upvotes: 3
Views: 1288
Reputation: 130
What purpose the unary plus operator serves here?
In C++, the behavior is laid out in section 5.3.1:
[2] The result of each of the following unary operators is a prvalue.
[7] The operand of the unary
+
operator shall have arithmetic, unscoped enumeration, or pointer type and the result is the value of the argument.
Sometimes people use this operator to "force" decay, i.e. in this case an array to pointer. But it is rather redundant since the conversion happens automatically.
What it does exactly here? Why it is not allowed in C?
Because the special meaning simply does not exist.
Upvotes: 6
Reputation: 18381
The section 6.5.3.3 of C99 states:
1) The operand of the unary + or - operator shall have arithmetic type; ......
2) The result of the unary + operator is the value of its (promoted) operand. The integer promotions are performed on the operand, and the result has the promoted type.
Pointers or arrays are not an arithmetic type.
Upvotes: 7
Reputation:
I have only ever seen this used in situations where the unary + operator has been overloaded in an OOP language like C++. It hasn't got a purpose in C apart from possible causing errors like this where a pointer was accidentally passed to a macro or a function that does not expect one.
Either way it's a nasty way to write code, if there was a good reason for it then it should be accompanied by an explanatory comment from the original author.
Upvotes: 0
Reputation: 20324
s
will be treated as a pointer not as an array when + operator is called.
For C, it seems that this concept was not introduced yet.
Upvotes: 0