Main Content

MISRA C:2012 Rule 12.3

The comma operator should not be used

Description

Note

Using Code Prover for checking coding rules is no longer supported. See Version History.

Rule Definition

The comma operator should not be used.

Rationale

The comma operator can be detrimental to readability. You can often write the same code in another form.

Troubleshooting

If you expect a rule violation but do not see it, refer to 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. For example, you could infer that jkl has a value abc+xyz, (abc+xyz)*(abc+xyz), f((abc+xyz),(abc+xyz)), and so on.
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: Advisory
AGC Category: Advisory

Version History

expand all