'How to properly return in a switch case? [closed]
Let suppose the following example:
int main()
{
int value=1;
switch( value )
{
case 1:
{
return 0;
} break;
default:
{
}
}
}
Returning from a switch
case is not structured programming, but early exit is considered by most developers as an acceptable deviation (wiki reference)
Most modern compilers will complain about this code because:
9: 'break' will never be executed
However, removing the break
sentence will trigger the question: "Is this a fallthrough? if yes, why is the [[fallthrough]]
attribute not specified?"
The obvious solution would be an hypothetical [[no_fallthrough]]
, but I found nothing in that direction.
My question is:
What is the appropriate approach in this case?
- Should return inside
switch
be avoided?- Should
break
be kept with the warning?- Should
break
be removed and a comment indicating the//[[no_fallthrough]]
?- Should
break
be removed and the developer notice that thereturn
statement is incompatible withbreak
, and cross-finger that no refactoring will break this.
Solution 1:[1]
However, removing the break sentence will trigger the question: "Is this a fallthrough?
The answer to the triggered question is: No, it does not fall through because it returns out of the function and thus out of the block that is inside the function.
Should return inside switch be avoided?
If you care about strict structured programming, then yes.
But as you quoted, most people consider it acceptable.
Should break be kept with the warning?
I recommend against control structures that have no effect, unless there is a good argument for using it. I see no good argument for having it here.
Should break be removed
I recommend this. A developer should be aware that return
does not fall through as much as break
, continue
(if switch is inside loop), throw
and goto
don't.
and cross-finger that no refactoring will break this.
In case of implicit fallthrough I recommend using the standard attribute [[fallthrough]]
if you use C++17 at least so that you don't have to rely on crossed fingers alone.
Otherwise use a warning is better than nothing.
Perhaps more interesting case is call to a [[noreturn]]
function:
// in some header
[[noreturn]] void fun();
case N:
fun();
// no fall through
I recommend at least commenting as shown, since familiarity with every function cannot be assumed. Functions don't tend to flip between noreturn and non-noreturn, but if that happens, implicit fallthough warning covers this case too.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | alkino |