Gotos in switches and Rule 6-4-5

Moderators: david ward, misra cpp

rgamble
Posts: 14
Joined: Fri Jul 20, 2007 7:54 pm

Gotos in switches and Rule 6-4-5

Postby rgamble » Fri Mar 01, 2019 5:39 pm

Consider the following example:

Code: Select all

typedef unsigned short uint16_t;
uint16_t foo(uint16_t x) {
    switch(x) {
        case 1:
            { goto end; }
        case 2:
            ++x;
            break;
        default:
            break;
    }   
end:
    ++x;
    return x;
}

The first case containing the goto appears to violate rule 6-4-5 which states that a case must end in a break or throw statement. If a break is added anywhere after the goto, it will be unreachable and would seemingly violate Rule 0-1-1 which forbids unreachable code. Rule 6-4-3 seems to consider the use of goto in a switch as it says that jump-statements (which includes goto) "are permitted within the compound statements forming the body of a switch-clause". Is it intended that an unconditional goto in a switch will require a deviation from either 6-4-5 or 0-1-1?

misra cpp
Posts: 145
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

Re: Gotos in switches and Rule 6-4-5

Postby misra cpp » Wed Apr 10, 2019 2:51 pm

You are right, your example violates 6-4-5.

When 6-4-3 says jump-statements (which includes goto) "are permitted within the compound statements forming the body of a switch-clause",
it means that you can write code like:
switch(x) {
case 1:
{ goto l1;
// some code
l1:
// more code
break;
}
case 2:
++x;
break;
default:
break;
}

not that you can use goto to leave the switch statement or jump out of the compound statement following the "case" keyword.
Posted by and on behalf of
the MISRA C++ Working Group


Return to “6.6 Statements (C++)”

Who is online

Users browsing this forum: No registered users and 3 guests