0

if I have

int arr[10] = { 1,2,3,4,5 };
std::cout << arr[1,4] << "\n";

the code compiles fine and returns 5 (arr[4]). This is true even with overloads of operator[] in different classes. In other words if I have:

class A{
public:
  int operator[](int i) {return i;}
}

A a;
std::cout<<a[1,4];

I will get 4 (a[4]). No compilation problem. Is there a way to avoid potential errors by a compilation error in such cases?

KMot
  • 467
  • 5
  • 13

1 Answers1

1

What you see here is the comma operator in action. The left operator is evaluated, its result is discarded and the result of the expression is the right operator.

Is there a way to avoid potential errors by a compilation error in such cases?

Well.. you could chose a custom type for the index and overload its comma operator. However, this is not recommended.

Instead, pay attention to your compiler warnings. For example gcc -Wall warns for this code:

int main(){
    int x = (1,2);
}

with

<source>:4:14: warning: left operand of comma operator has no effect [-Wunused-value]

4 |     int x = (1,2);

  |              ^
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185