c++ – Why is comma in indexing deprecated in C ++ 20?

Question:

Why in C ++ 20, the use of the operator , in the indexation statement array [] has become obsolete?

For example, the following use-case now generates a warning :

#include <cstddef>
#include <iostream>

int a[42 + 1];

void logging(std::size_t index) {
    std::cout << "[Array access: " << index << "]\n";
}

int main() {
    std::size_t index = 42;
    std::cout << a[logging(index), index] << '\n';
}

warning: top-level comma expression in array subscript is deprecated [-Wcomma-subscript]

Answer:

I think there were no problems and was not confused with tuple .

As @ andrey-sv pointed out, this is indirectly mentioned here .

UPD

I will add a free partial translation of the article.

P1161R3 Deprecate uses of the comma operator in subscripting expressions

Abstract

We propose to deprecate the use of the comma operator in subscripting expressions as they are not very useful, confusing and limit futures evolutions of the standard.

Annotation.

We suggest avoiding the use of the comma operator in index expressions because they are not very useful, confusing, and limit the development of the future standard.

Текуший 
array[x]     // Ok
array[(x,y)] // Ok, если y это index/key
array[x,y]   // Ok, если y это index/key

Предлагаемый
array[x]      // Ok
array[(x,y)]  // Ok, если y это index/key
array[x,y]    // Устаревший, если y это index/key

Currently, a comma can appear in subscript expressions such that auto z = foo[x, y] calls the comma operator with y as the argument. While this is currently unambiguous, it is confusing when encountered and error-prone when used.

The authors think this syntax would be more useful and suited to index multidimensional classes such as mdspan .

Currently, a comma in index expressions such as auto z = foo[x, y] invokes the comma operator with y as an argument. While this currently looks unambiguous, it is confusing and error prone to use.

The authors believe this syntax will be more useful and suitable for indexing multidimensional classes such as mdspan .

mdspan<int, array_property::dimension<2, 3, 5>> foo(/*...*/);
int value = foo[1, 2, 3];

In contexts where comma is given a special meaning, [Example: in lists of arguments to functions ([expr.call]) and lists of initializers ([dcl.init]) – end example] the comma operator as described in this subclause can appear only in parentheses.

In cases where the comma has a special meaning, [Example: in function argument lists ([expr.call]) and initializer lists ([dcl.init]) – end of example] the comma operator, as described in this subclause, can only appear in brackets.

Scroll to Top