This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 9.6.2 - A goto statement shall reference a label in a surrounding block
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
A goto statement shall be enclosed in a statement that directly encloses [1] its referenced label.
Rationale
The unconstrained use of goto can lead to programs that are extremely difficult to comprehend and analyse. However, flags may need to
be introduced to give the required control flow when it is not used, with the possibility that the flags may themselves make the code less transparent
than if goto were used. The restricted use of goto is therefore allowed where that use will not lead to semantics contrary
to developer expectations.
This rule prohibits jumping in to nested blocks, as this results in complex control flow.
Example
void f1()
{
int32_t j = 0;
goto L1; // Non-compliant
for ( j = 0; j < 10 ; ++j )
{
L1:
j;
}
}
void f2()
{
for ( int32_t j = 0; j < 10 ; ++j )
{
for ( int32_t i = 0; i < 10; ++i )
{
goto L2; // Compliant
}
}
L2:
f1();
}
switch ( i )
{
case 0:
if ( x < y )
goto L3; // Non-compliant
break;
case 1:
L3:
break;
}
Glossary
[1] Directly enclose
See enclose [2].
[2] Enclose
A statement S1 directly encloses [1] a statement S2 if:
-
S1 is a labeled-statement, and S2 is the contained statement; or
-
S1 is a compound-statement, and S2 is any statement of its statement-seq; or
-
S1 is a selection-statement, and S2 is any of its statements (but not its init-statement); or
-
S1 is an iteration-statement, and S2 is the contained statement (but not an init-statement).
A statement S1 encloses a statement S2 if:
-
S1 directly encloses [1] S2; or
-
S1 directly encloses [1] a statement S3 and S3 encloses S2.
Copyright The MISRA Consortium Limited © 2023