+ 2

# <SOLVED> weird (int)[array] or (int)[ T* ] operation

Recently i did a challenge where i one of the rounds I had to find the output on this code: int x[5]={1,2,3,4,5}; std::cout<<3[x]<<std::endl; the answer was: 4 is the (int)[int*] or (int)[int[]] a valid operation? Is it a UB? And why is that the output?

6 Answers

+ 4

<arrray>[<index>]
<index>[<array>]
*(<array> + <index>)
*(<index> + <array>)
Are alike, so for your case here, 3[x] is similar to x[3]. And the element at 3rd index is 4. Odd isn't it? I was also so confused about this once XD
(Edited)

+ 4

the compiler converts the array operation in pointers before accessing the array elements, which means:
array[index] == *(array + index);
therefore x[3] will evaluate to โ *(x+3), and 3[x] will evaluate to โ *(3 + x) which is the same as *(x + 3) "addition is commutative", so output will be 4.
NOTE: donโt use this syntax in real code. this only works for the built-in subscript operator.

+ 3

It looks like an alternate way to access the elements in the array. Its the same as x[3]

+ 2

xaralampis_
It's also the same when we do
3[x]
We can also see it like this,
*(3 + x)
Or like this,
*(x + 3)
The literal 3 can be put before or after <x>.

+ 1

Ipang Yeah, it is... the plus and dereference wayo was familiar to me sure. But I had never seen the second one before

+ 1

Mohamed ELomari that makes a lot of sence