1

While studying 18 Essential C++ Interview Questions, I found a question with the following (strange) statement:

std::cout << (1 + 3)[a] - a[0] + (a + 1)[2];

The answer then explained, (1+3)[a] is the same as a[1+3], which is still strange for me.

May I ask for the history of this? Why it's so and how it helps to allow this?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • @πάντα ῥεῖ I think this question should not be considered a duplicate of the linked question because it's about C++ and not C. – Brian Bi Feb 04 '17 at 01:09
  • @Brian Feel free to vote for reopening. – πάντα ῥεῖ Feb 04 '17 at 01:11
  • No need from the looks of it. Looks like someone used the dupe anvil. – user4581301 Feb 04 '17 at 01:12
  • Yeah I just reopened it by myself. I was just leaving a comment to explain my reasoning – Brian Bi Feb 04 '17 at 01:12
  • Wandering a smidgen off to the left a bit, but anyone know why C allows this? I grok the math, but grammatically it is a bit of a mindfreak. I always figured it was either for mathematical consistency or because the value of disallowing it was far less than the value of the added compiler complexity required to disallow it. – user4581301 Feb 04 '17 at 01:27
  • It allows it because there's no reason not to allow it. This is like asking why 2+1 should be 3 when 1+2 is also 3. The answer is because + means the same both ways, and that's the end of it. Why make a rule to ban it? – Lightness Races in Orbit Feb 04 '17 at 01:39

1 Answers1

14

In C, a[i] is defined to mean *(a + i). Based on this definition you can see that a[i] and i[a] mean the same thing.

C++ inherited this "feature" from C, however, note that in C++:

  • i[a] and a[i] only mean the same thing if they don't call overloaded operators; for example the code you posted will not work if a has type std::vector<int>.
  • In C++14 and above, a[i] is not identical to *(a + i) since the former is not always an lvalue.
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • In which case in C++14 and above is a[i] not an lvalue? Just curious. – Alex Telon Feb 04 '17 at 02:19
  • 2
    @AlexTelon a[i] is an [_xvalue_](http://en.cppreference.com/w/cpp/language/value_category#xvalue) if a is an array _rvalue_. See also [built-in_subscript_operator](http://en.cppreference.com/w/cpp/language/operator_member_access#Built-in_subscript_operator). – Spectral Sequence Feb 04 '17 at 06:23