2

A patch was posted to gcc that provides something called vector subscripting to g++ (gcc already had it).

If a is an array and i is an int then i[a] is legal and equal to a[i].

double a[]{0.0, 1.0, 2.0, 3.0}; // C++11 style but would work in C++98 style too.
assert(a[2] == 2.0);
assert(2[a] == 2.0);

So, is this legal and standard C/C++ or is it a gcc extension?

Actually, Google shows MS Developer Studio has this too. I looked in the C++ standard and didn't see it though.

Henrik
  • 23,186
  • 6
  • 42
  • 92
emsr
  • 15,539
  • 6
  • 49
  • 62
  • 4
    Since `*(ptr+i)` and `ptr[i]` expressions are identical, the answer flows nicely from the commutativity of addition. If I see anyone on my team use this "feature", he'll be fired on the spot. – Sergey Kalinichenko Apr 18 '12 at 14:41
  • Yes, it's counter-intuitive and would surprise people looking through code. Also, luckily it works by pointer arithmetic rather than some lexical rule so it won't work for, say, std::vector or std::array. – emsr Apr 18 '12 at 15:14
  • possible duplicate of [In C arrays why is this true? a\[5\] == 5\[a\]](http://stackoverflow.com/questions/381542/in-c-arrays-why-is-this-true-a5-5a) – Bo Persson Apr 18 '12 at 15:52

3 Answers3

11

The patch has nothing to do with i[a] being equivalent to a[i]; that has always been the case, in both languages. Unless user-defined types are involved, a[i] is defined as being equivalent to *(a+i), and addition is commutative.

The patch concerns vector datatypes (not to be confused with the C++ std::vector class template), a GCC language extension to support vector processing instructions. According to the patch notes, they were subscriptable like arrays in C but not C++, and this patch adds that feature to C++.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Yet another "I'll be ... WTF" moment in my C++ travels. I see the rationale for this syntax too. Thx. – emsr Apr 18 '12 at 15:04
  • OK, I finally followed the standard to expr.add p5 and dcl.array p6 where they say this. – emsr Apr 18 '12 at 15:06
  • not to be pedantic, but don't you mean that `a[i]` is `*(a+i)` for primitives or something like that? Because from what you are saying it sounds like a class with an dereference and addition operator would automatically get an `operator[]` which is obviously not the case. – Grizzly Apr 18 '12 at 15:43
5

In C, this follows from the fact that a[b] is equivalent to *(a + b), which since + is commutative of course is the same as *(b + a).

unwind
  • 391,730
  • 64
  • 469
  • 606
3

Yes this is legal, as vector elements are assured to be contiguous in memory by the standard.

Note that:

a[i] == i[a] == *(a+i)
Alok Save
  • 202,538
  • 53
  • 430
  • 533