Main Content

MISRA C++:2023 Rule 9.6.3

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

Since R2024b

Description

Rule Definition

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

Rationale

Using a goto statement to jump to a label earlier in the same function body creates an iteration. Avoid creating iterations by using goto statements. Use iteration statements defined by the core language because they are easier to understand and maintain than goto statements.

Polyspace Implementation

Polyspace® raises this defect when an iteration is formed by using goto statements.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include<iostream>
void foo(int x, int y)
{
test:
	x++;
	if (x <= y) {
		std::cout << x << std::endl;
		goto test;   //Noncompliant
	}
}

Because goto test sends the code back to the beginning of the function, the goto statement creates a loop. Use looping statements such as while or for instead.

#include<iostream>
void foo(int x, int y)
{
	while (x < y)
	{
		x++;
		std::cout << x << std::endl;
	}
}

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2024b