2

What happens when we interchange the array name and index like index[arrayname] in C++? Is arrayname[index] the same as writing index[arrayname]? What will be the value in both?

  • @NathanOliver That's a C answer. The answer is more complicated in C++, no? – John Kugelman Dec 03 '21 at 16:33
  • 2
    @JohnKugelman Nope. This is something that is the same in both C and C++. – NathanOliver Dec 03 '21 at 16:33
  • 1
    If the array is actually a `std::vector`, `std::array`, or some other array-like class with operator overloading, they can't be swapped. The trick doesn't translate so well to C++. – John Kugelman Dec 03 '21 at 16:35
  • 1
    @JohnKugelman The op says they have an array, not a vector. This only works with an array, so they must have been using an array. – NathanOliver Dec 03 '21 at 16:36
  • It could be a `std::array`. – John Kugelman Dec 03 '21 at 16:37
  • @JohnKugelman It wouldn't compile if it was a `std::array`. – NathanOliver Dec 03 '21 at 16:42
  • Dupe target: https://stackoverflow.com/questions/381542/with-arrays-why-is-it-the-case-that-a5-5a – NathanOliver Dec 03 '21 at 16:42
  • 1
    _"...The built-in subscript expression E1[E2] is exactly identical to the expression *(E1 + E2)..."_ so `E1[E2] == *(E1 + E2) == *(E2 + E1) == E2[E1]` see __Built-in subscript operator___ here https://en.cppreference.com/w/cpp/language/operator_member_access – Richard Critten Dec 03 '21 at 16:43
  • 3
    What I'm getting at is an answer for C++ should be along the lines of, "If you have a plain array then `array[index]` and `index[array]` are interchangeable. However, this trick doesn't work in general for other array-like types that overload `operator[]` like `std::array` or `std::vector`." And of course there should be a bunch of explanation. – John Kugelman Dec 03 '21 at 16:43
  • 3
    We're always telling people that C and C++ are different languages. We shouldn't be closing this C++ question as a duplicate of a C question. The answers are different. – John Kugelman Dec 03 '21 at 16:47
  • 1
    Despite being tagged C, the linked Q&A already has an answer explaining that this doesn't work with overloaded `[]`. :/ – HolyBlackCat Dec 03 '21 at 17:05

2 Answers2

4

For builtin types, the definition of E1[E2] "is identical (by definition) to" *((E1) + (E2)). (quotation from [expr.sub]/1) So the answer is simple: interchanging the names has no effect.

For user-defined types, E1 has to be a class type with an overloaded operator[], so, absent some funky stuff, you can't interchange the two expressions.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
1

It has no effect since arrayname[index] is identical writing as index[arrayname] cause both are interpreted as: *(arrayname + index)