Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are vector subscripts standard C/C++?

Tags:

c++

gcc

g++

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.

like image 754
emsr Avatar asked Aug 31 '26 21:08

emsr


2 Answers

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

like image 84
Mike Seymour Avatar answered Sep 02 '26 12:09

Mike Seymour


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).

like image 30
unwind Avatar answered Sep 02 '26 13:09

unwind