Main Content

MISRA C:2012 Rule 13.3

A full expression containing an increment (++) or decrement (--) operator should have no other potential side effects other than that caused by the increment or decrement operator

Description

Rule Definition

A full expression containing an increment (++) or decrement (--) operator should have no other potential side effects other than that caused by the increment or decrement operator.

Rationale

The rule is violated if the following happens in the same line of code:

  • The increment or decrement operator acts on a variable.

  • Another read or write operation is performed on the variable.

For example, the line y=x++ violates this rule. The ++ and = operator both act on x.

Although the operator precedence rules determine the order of evaluation, placing the ++ and another operator in the same line can reduce the readability of the code.

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

int input(void);
int choice(void);
int operation(int, int);

int func() {
    int x = input(), y = input(), res;
    int ch = choice();
    if (choice == -1)
        return(x++);               // Noncompliant
    if (choice == 0) {
        res = x++ + y++;           // Noncompliant
        return(res);
    }
    else if (choice == 1) {
        x++;                       // Compliant
        y++;                       // Compliant
        return (x+y);
    }
    else {
        res = operation(x++,y);    // Noncompliant
        return(res);
    }
}

In this example, the rule is violated when the expressions containing the ++ operator have side effects other than that caused by the operator. For example, in the expression return(x++), the other side-effect is the return operation.

Check Information

Group: Side Effects
Category: Advisory
AGC Category: Readability

Version History

Introduced in R2014b

expand all