Main Content

MISRA C:2012 Rule 15.2

The goto statement shall jump to a label declared later in the same function

Description

Note

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

Rule Definition

The goto statement shall jump to a label declared later in the same function.

Rationale

Unrestricted use of goto statements makes the program unstructured and difficult to understand. You can use a forward goto statement together with a backward one to implement iterations. Restricting backward goto statements ensures that you use only iteration statements provided by the language such as for or while to implement iterations. This restriction reduces visual complexity 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

void foo(void) {
    int i = 0, result = 0;

label1:
    for ( i; i < 5; i++ ) {
        if (i > 2) goto label2;   /* Compliant */
    }

label2: {
        result++;
        goto label1;               /* Non-compliant */
    }
}

In this example, the rule is violated when a goto statement causes a backward jump to label1.

The rule is not violated when a goto statement causes a forward jump to label2.

Check Information

Group: Control Flow
Category: Required
AGC Category: Advisory

Version History

Introduced in R2014b

expand all