r/ProgrammerTIL • • Sep 14 '17

Other [c++] Array declarations are commutative/invertible.

array[4] is equivalent to 4[array]. Not that you would ever really use it.

43 Upvotes

14 comments sorted by

View all comments

Show parent comment

1

u/GiantRobotTRex Sep 14 '17 edited Sep 14 '17

Is 3[4] valid?

Edit: Apparently not (at least with gcc)

source_file.cpp:7:21: error: invalid types ‘int[int]’ for array subscript std::cout << 3[4];

8

u/redditsoaddicting Sep 14 '17

No, neither of those is implicitly convertible to a pointer.

2

u/uptotwentycharacters Sep 14 '17

No, because array indexing is syntactic sugar for pointer arithmetic, and pointer arithmetic requires one operand to be a pointer type and the other to be integral type (the order doesn't matter though).

1

u/Tarrjue Sep 14 '17

Even without the typing, this probably wouldn't work. You would almost certainly run into a seg fault.

2

u/GiantRobotTRex Sep 14 '17

Either 3 or 4 would probably be replaced by the fixed address of a hardware device or something.

1

u/IbanezDavy Oct 12 '17 edited Oct 12 '17

Nope, but last I checked,

3[arr] should be ok, for the same reason as describe in this post.