What does "int* p=+s;" do?
C++ArraysPointersUnary OperatorC++ Problem Overview
I saw a weird type of program here.
int main()
{
int s[]={3,6,9,12,18};
int* p=+s;
}
Above program tested on GCC and Clang compilers and working fine on both compilers.
I curious to know, What does int* p=+s;
do?
Is array s
decayed to pointer type?
C++ Solutions
Solution 1 - C++
Built-in operator+
could take pointer type as its operand, so passing the array s
to it causes array-to-pointer conversion and then the pointer int*
is returned. That means you might use +s
individually to get the pointer. (For this case it's superfluous; without operator+
it'll also decay to pointer and then assigned to p
.)
(emphasis mine) > The built-in unary plus operator returns the value of its operand. The only situation where it is not a no-op is when the operand has integral type or unscoped enumeration type, which is changed by integral promotion, e.g, it converts char to int or if the operand is subject to lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversion.
Solution 2 - C++
Test this:
#include <stdio.h>
int main(){
char s[] = { 'h', 'e', 'l', 'l', 'o' , ' ', 'w', 'o', 'r', 'l', 'd', '!'} ;
printf("sizeof(s) : %zu, sizeof(+s) : %zu\n", sizeof(s), sizeof(+s) ) ;
}
On my PC (Ubuntu x86-64) it prints:
sizeof(s): 12, sizeof(+s) : 8
where
12 = number of elements s times size of char, or size of whole array
8 = size of pointer
Solution 3 - C++
That's a unary plus symbol which has no practical effect here. For example:
#include <iostream>
int main() {
int a[] = {1};
std::cout << a << " " << +a << std::endl;
}
This prints the same address for both a
and +a
. The array is decayed to pointer as usual.
Note that, if it had been an unary minus -a
instead then GCC would show the error:
error: wrong type argument to unary minus
Edit: Though it has no effect in OP's code, a
and +a
are not exactly same. Please refer to the answers by Khurshid Normuradov and songyuanyao for details.
Solution 4 - C++
> Is array s
decayed to pointer type?
Yes.
> What does int* p=+s;
do?
Unary +
operator forces the array to decay to a pointer.
C++ Standard, 5.3.1 Unary operators(P7):
> 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.
The unary +
form (+s)
forces the operand to be evaluated as a number or a pointer.
For more information, please see this stack overflow answer.
Solution 5 - C++
Here unary + is just making *p to point the addresses of Integer array. Let's take two array s1 and s2
int s1[]={1,5,2};
int s2[]={2,5,2};
int *p=+s1;
p=+s2;
printf("%d",(int)p[0]);
Output: 2
So in my point of view unary + is just making pointer p to point the array s beginning address.