What does "int* p=+s;" do?

msc picture msc · May 30, 2018 · Viewed 7.4k times · Source

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?

Answer

songyuanyao picture songyuanyao · May 30, 2018

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.