Main Content

AUTOSAR C++14 Rule M5-18-1

The comma operator shall not be used

Description

Rule Definition

The comma operator shall not be used.

Rationale

The comma operator takes two operands. It evaluates the operators from left to right, discards the value of the left operand, and returns the value of the right operand. This operator has the lowest operator precedence. These properties can make the use of the comma operator nonintuitive. For instance, consider this code:

array[i++,j] = 1
At a glance, it might appear that the preceding code accesses a multidimensional array. In fact, this code is equivalent to:
i++;
array[j] = 1;
The use of the comma operator makes the code difficult to read and maintain. To avoid confusion, do not use the comma operator. Refactor the expression into multiple statements instead.

Polyspace Implementation

Polyspace® flags the use of comma operator. Violations are not raised when you use comma operator for function calls and initializations.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

typedef signed int abc, xyz, jkl;
static void func1 ( abc, xyz, jkl );       /* Compliant - case 1 */
int foo(void)
{
    volatile int rd = 1;                   /* Compliant - case 2*/
    int var=0, foo=0, k=0, n=2, p, t[10];  /* Compliant - case 3*/
    int abc = 0, xyz = abc + 1;            /* Compliant - case 4*/
    int jkl = ( abc + xyz, abc + xyz );    /* Noncompliant - case 1*/
    var = 1, foo += var, n = 3;          /* Noncompliant - case 2*/ 
    var = (n = 1, foo = 2);              /* Noncompliant - case 3*/
    for ( int *ptr = &t[ 0 ],var = 0 ;
          var < n; ++var, ++ptr){}    /* Noncompliant - case 4*/
    if ((abc,xyz)<0) { return 1; }         /* Noncompliant - case 5*/
}

In this example, the code shows various uses of commas in C code.

Noncompliant Cases
CaseReason for noncompliance
1When reading the code, it is not immediately obvious what jkl is initialized to.
2When reading the code, it is not immediately obvious whether foo has a value 0 or 1 after the statement.
3When reading the code, it is not immediately obvious what value is assigned to var.
4When reading the code, it is not immediately obvious which values control the for loop.
5 When reading the code, it is not immediately obvious whether the if statement depends on abc, xyz, or both.
Compliant Cases
CaseReason for compliance
1Using commas to call functions with variables is allowed.
2Comma operator is not used.
3 & 4When using the comma for initialization, the variables and their values are immediately obvious.

Check Information

Group: Expressions
Category: Required, Automated

Version History

Introduced in R2019a