I am quite confused with the comma operator. I have never seen such code with such syntax? but I am curious if it useful at any place? why is it deprecated in c++20?
#include <iostream>
int main()
{
int a[5]{1,2,3,45,5};
std::cout << a[(2,3)] <<'\n'; // this is work , in c++17 works
std::cout << a[2,3] << '\n'; // but this is deprecated in c++20 ,in c++17 works
return 0;
}
It's important to recognize the difference between comma as an expression operator and comma as a separator between grammatical terms of some kind. They use the same punctuation, but they don't have the same meaning.
Within the {}
of a braced-init-list, individual terms are separated by commas. So {1,2,3,45,5}
is a sequence of terms. That's a comma-as-separator.
However, within a general expression, the comma acts as an expression operator. When a comma is an expression operator between two expression terms, it means to evaluate the left expression, discard its result, then evaluate the right expression, which is the result of the total expression.
Within a []
, a comma is not a separator in C++17. Therefore, it acts as an expression operator. a[2,3]
means to evaluate 2, discard it, then evaluate 3. So the index used will be 3.
C++20 deprecates a comma expression as the direct expression used in a []
. It does this so that future versions of the C++ standard will have the freedom to make commas within []
become comma separators rather than comma operators. That is, [2, 3]
makes 2 and 3 the parameters to a call to an overloaded operator[]
.
This is similar to how the parameters to a function use the separator comma. So if you need to use the operator comma on two expressions within a function call, you have to wrap them in ()
: func(1, (2, 3))
. This function takes two parameters, with the second one being the result of the comma operator applied to its terms.