Why is this an issue?
The comma operator takes two expressions, executes them from left to right, and returns the result of the second one. The use of this operator is
generally detrimental to the readability and reliability of code, and the same effect can be achieved by other means.
It is especially error-prone in array subscripts where it might be misinterpreted as accessing a multidimensional array. The use of a comma in this
context is deprecated since C++20 (it might be repurposed in a later edition of the standard to actually access multidimensional arrays, but until
then, it should really not be used).
Noncompliant code example
i = a += 2, a + b; // Noncompliant. What's the value of i ?
a[1, 2] = 3; // Noncompliant: 1 is ignored. This is not an access to a multidimensional array.
x = a[i++, j = i + 1, j*2]; // Noncompliant. What index is used for a?
Compliant solution
a += 2;
i = a + b;
j = i + 1;
x = a[j*2];
++i;
Exceptions
Use of comma operator is tolerated in initialization and increment expressions of for
loops.
for(i = 0, j = 5; i < 6; i++, j++) { ... }
Resources
- MISRA C:2004, 12.10 - The comma operator shall not be used.
- MISRA C++:2008, 5-18-1 - The comma operator shall not be used.
- MISRA C:2012, 12.3 - The comma operator should not be used