Main Content

MISRA C:2023 Rule 15.4

There should be no more than one break or goto statement used to terminate any iteration statement

Since R2024a

Description

Rule Definition

There should be no more than one break or goto statement used to terminate any iteration statement.

Rationale

If you use one break or goto statement in your loop, you have one secondary exit point from the loop. Restricting number of exits from a loop in this way reduces visual complexity of your 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

volatile int stop;

int func(int *arr, int size, int sat) {
    int i,j;
    int sum = 0;
    for (i=0; i< size; i++) {   /* Compliant  */
        if(sum >= sat)
            break;
        for (j=0; j< i; j++) {  /* Compliant */
            if(stop)
                break;
            sum += arr[j];
        }
    }
}

In this example, the rule is not violated in both the inner and outer loop because both loops have one break statement each.

volatile int stop;

void displayStopMessage();

int func(int *arr, int size, int sat) {
    int i;
    int sum = 0;
    for (i=0; i< size; i++) {
        if(sum >= sat)
            break;
        if(stop)
            goto L1;   /* Non-compliant  */
        sum += arr[i];
    }
    
    L1: displayStopMessage();
}

In this example, the rule is violated because the for loop has one break statement and one goto statement.

volatile int stop;

void displayMessage();

int func(int *arr, int size, int sat) {
    int i,j;
    int sum = 0;
    for (i=0; i< size; i++) {
        if(sum >= sat)
            break;
        for (j=0; j< i; j++) { /* Compliant */
            if(stop)
                goto L1;  /* Non-compliant */ 
            sum += arr[i];
        }
    }
   
    L1: displayMessage();
}

In this example, the rule is not violated in the inner loop because you can exit the loop only through the one goto statement. However, the rule is violated in the outer loop because you can exit the loop through either the break statement or the goto statement in the inner loop.

Check Information

Group: Control Flow
Category: Advisory
AGC Category: Advisory

Version History

Introduced in R2024a