Main Content

MISRA C:2012 Rule 15.3

Any label referenced by a goto statement shall be declared in the same block, or in any block enclosing the goto statement

Description

Note

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

Rule Definition

Any label referenced by a goto statement shall be declared in the same block, or in any block enclosing the goto statement.

Rationale

Unrestricted use of goto statements makes the program unstructured and difficult to understand. Restricting use of goto statements to jump between blocks or into nested blocks reduces visual code complexity.

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 f1(int a) {
    if(a <= 0) {
        goto L2;        /* Non-compliant - L2 in different block*/
    }
    
    goto L1;            /* Compliant - L1 in same block*/

    if(a == 0) {
        goto L1;        /* Compliant - L1 in outer block*/
    }

    goto L2;            /* Non-compliant - L2 in inner block*/

    L1: if(a > 0) {
            L2:;
    }
}

In this example, goto statements cause jumps to different labels. The rule is violated when:

  • The label occurs in a block different from the block containing the goto statement.

    The block containing the label neither encloses nor is enclosed by the current block.

  • The label occurs in a block enclosed by the block containing the goto statement.

The rule is not violated when:

  • The label occurs in the same block as the block containing the goto statement..

  • The label occurs in a block that encloses the block containing the goto statement..

void f2 ( int x, int z ) {
    int y = 0;

    switch(x) {
    case 0:
        if(x == y) {
            goto L1;  /* Non-compliant - switch-clauses are treated as blocks */
        }
        break;
    case 1:
        y = x;
        L1: ++x;
        break;
    default:
        break;
    }

}

In this example, the label for the goto statement appears to occur in a block that encloses the block containing the goto statement. However, for the purposes of this rule, the software considers that each case statement begins a new block. Therefore, the goto statement violates the rule.

Check Information

Group: Control Flow
Category: Required
AGC Category: Advisory

Version History

Introduced in R2014b

expand all