Today, I came across the notation 3[arr]
in C++, and I was surprised to find out that it's a valid way to access array elements. For example:
int arr[] = {10, 20, 30};
int element = 1[arr]; // This compiles and works!
Online IDE: https://onlinegdb.com/4o8qnsx8O
The assembly of this looks exactly same
arr:
.long 10
.long 20
.long 30
main:
push ebp
mov ebp, esp
sub esp, 16
mov eax, DWORD PTR arr+4 ; getting 20 from arr variable, store in eax
mov DWORD PTR [ebp-4], eax ; store eax to variable "a"
mov eax, DWORD PTR arr+4 ; getting 20 from arr variable, store in eax
mov DWORD PTR [ebp-8], eax ; store eax to variable "b"
mov eax, 0
leave
ret
Disassembly from Godbolt: https://godbolt.org/z/dEaYjashs
While this notation seems to work, it's somewhat unconventional, and I'm curious if it's considered a good practice in C++ programming. In natural language, we say "Accessing 3rd element of array arr", then isn't 3[arr]
notation fits better here?
My questions are:
- Is using
3[arr]
a valid and safe practice in C++? - Are there any specific situations or use cases where this notation might be advantageous?
- Is there any guideline or convention against using
3[arr]
that I should be aware of?
I haven't encountered this notation in any code I've seen so far, so any insights or advice on its usage would be greatly appreciated.
a[i]
is simply the memory locationa + i
. $\endgroup$i[a]
. $\endgroup$