+ 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?

16th Mar 2020, 4:53 PM
xaralampis_
xaralampis_ - avatar
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)
16th Mar 2020, 5:10 PM
Ipang
+ 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.
16th Mar 2020, 5:45 PM
MO ELomari
MO ELomari - avatar
+ 3
It looks like an alternate way to access the elements in the array. Its the same as x[3]
16th Mar 2020, 5:12 PM
Pete Cowling
Pete Cowling - avatar
+ 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>.
16th Mar 2020, 5:33 PM
Ipang
+ 1
Ipang Yeah, it is... the plus and dereference wayo was familiar to me sure. But I had never seen the second one before
16th Mar 2020, 5:17 PM
xaralampis_
xaralampis_ - avatar
+ 1
Mohamed ELomari that makes a lot of sence
16th Mar 2020, 5:48 PM
xaralampis_
xaralampis_ - avatar