Trivia impact: rare
The Comma That Picks the Subscript
two expressions between brackets, but only one index
int scores[] = {10, 20, 30};
int index = 0;
std::cout << scores[index++, 2] << "\n";
std::cout << index << "\n";
Does this compile? What does it print?
Answer
It compiles cleanly as C++17 under -Wall -Wextra: the increment happens, then the array
is indexed with 2.
Why¶
In C++17, [expr.sub] puts one expression inside built-in subscript brackets. Here that
expression is index++, 2, which [expr.comma] evaluates left-to-right and whose value and
type come from its right operand. The result is therefore scores[2], after index has
been incremented; it is not two array indices or an overloaded multi-argument subscript.
This differs from a reversed built-in subscript, where pointer addition makes
2[scores] legal instead.
Where it shows up¶
It turns up mostly in old macros, generated code, and deliberate C-family cleverness.
C++23 added multi-argument operator[], so overloaded bracket syntax can mean something
different there; this entry deliberately demonstrates the C++17 built-in-array rule.
Takeaway: in a C++17 built-in subscript, a comma expression yields its right-hand index.
Try it: g++ -std=c++17 main.cpp -o demo && ./demo