3 ms·
What this is talking about is the behavior of [] in C and C++. In these x[y] and y[x] are the same. I was first introduced to this by a friend of mi
by olliej 4y ago
What this is talking about is the behavior of [] in C and C++. In these
x[y]
and
y[x]
are the same. I was first introduced to this by a friend of mine many many years ago (because I'm an old) as
for (i = 0; etc)
putc(i["hello world"])
or similar nonsense.
The C++ change that makes this matter is that apparently pre c++17 doesn't enforce sequencing such that expression1[expression2] doesn't require expression1 be evaluated before expression2. C++17 does actually fix the sequencing to be left to right, so now expression1[expression2] will always evaluate as expression1;expression2 and expression2[expression1] will always evaluated as expression2;expression1 without depending on UB.
- jbverschoor 4y agoI’ve never seen that before. Luckily
- olliej 4y agoHe was also a tutor/TA and I think mostly used it to explain how pointers vs. indexing worked. Or possibly to traumatize students :D
- int_19h 4y agoIt is extremely rare even in ancient C code. The only reason why it exists in C at all is because rewriting a[i] as *(a+i) was inherited by C from B; the latter only has a single machine word type for everything, so there was no way to define it such that a[i] would be legal but i[a] would be illegal in B.
- HelloNurse 4y agoIn the competing array indexing syntax *(a+b) there is the same evaluation order issue, and they should have the same behaviour: is a evaluated before b or the compiler is allowed to choose an order? Clearly it depends on the rules for a+b which are more important than the special case of array indexing.