59

I've seen a suggested coding standard that reads Never use goto unless in a switch statement fall-through.

I don't follow. What exactly would this 'exception' case look like, that justifies a goto?

Brent Arias
  • 29,277
  • 40
  • 133
  • 234

7 Answers7

115

This construct is illegal in C#:

switch (variable) {
   case 2: 
       Console.WriteLine("variable is >= 2");
   case 1:
       Console.WriteLine("variable is >= 1");
}

In C++, it would run both lines if variable = 2. It may be intentional but it's too easy to forget break; at the end of the first case label. For this reason, they have made it illegal in C#. To mimic the fall through behavior, you will have to explicitly use goto to express your intention:

switch (variable) {
   case 2: 
       Console.WriteLine("variable is >= 2");
       goto case 1;
   case 1:
       Console.WriteLine("variable is >= 1");
       break;
}

That said, there are a few cases where goto is actually a good solution for the problem. Never shut down your brain with "never use something" rules. If it were 100% useless, it wouldn't have existed in the language in the first place. Don't use goto is a guideline; it's not a law.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • 3
    @Mehrdad: I would love to read "Never shut down your brain" but I think Im kinda late for it.. It seems it has been removed. Is that possible to refresh the link if you have any other reference link by chance? Thanks – curiousBoy Sep 10 '14 at 19:02
  • 1
    @curiousBoy Unfortunately, I do not recall what it was after more than 3 years and I do not have enough rep on access programmers.stackexchange to see it (I suspect it used to be a Stack Overflow post I linked to). – Mehrdad Afshari Sep 10 '14 at 22:16
  • 2
    That is unfortunate, even 5 years after the initial post it is still relevant – ThrowingDwarf Mar 31 '16 at 06:48
  • Shame that link for "Never shut down your brain" is gone. I wish SO would allow certain opinionated questions and answers as it makes life fun. Here's a similar question http://stackoverflow.com/questions/406760/whats-your-most-controversial-programming-opinion?page=1&tab=votes#tab-top – Matthew Lock May 02 '17 at 03:39
  • Found it, https://stackoverflow.com/questions/406760/whats-your-most-controversial-programming-opinion edited Jan 9 '09 at 15:52 Steven Robbins (https://stackoverflow.com/users/26507) Just in case, the original comment is below. Camel case at the beginning to get around more restrictive character limit than existed in '09 – Jessica Pennell Jun 09 '17 at 18:20
  • 2
    TheOnly "best practice" youShouldBeUsingAllTheTimeIs "Use Your Brain". Too many people jumping on too many bandwagons and trying to force methods, patterns, frameworks etc onto things that don't warrant them. Just because something is new, or because someone respected has an opinion, doesn't mean it fits all :) EDIT: Just to clarify - I don't think people should ignore best practices, valued opinions etc. Just that people shouldn't just blindly jump on something without thinking about WHY this "thing" is so great, IS it applicable to what I'm doing, and WHAT benefits/drawbacks does it bring? – Jessica Pennell Jun 09 '17 at 18:21
  • I'm not cool enough to edit that 406760 link into Mehrdad Afshari's answer, if someone with enough karma could and could delete this comment it would be appreciated by everyone I'm sure. – Jessica Pennell Jun 09 '17 at 18:27
  • I was recently coding an Item generator, and for Legendary items, if no matching base type exists, I use goto to ensure the player gets a rare quality item instead. It certainly beats a convoluted recursion mechanism. – Krythic Jul 30 '19 at 04:10
  • I'd love the evil. Thanks.. Gonna to use it now! – jeffbRTC Feb 13 '21 at 06:43
  • There is also `goto default;`. – Jonas Äppelgran May 18 '22 at 08:22
26

C# refuses to let cases fall through implicitly (unless there is no code in the case) as in C++: you need to include break. To explicitly fall through (or to jump to any other case) you can use goto case. Since there is no other way to obtain this behaviour, most (sensible) coding standards will allow it.

switch(variable)
{
case 1:
case 2:
    // do something for 1 and 2
    goto case 3;
case 3:
case 4:
    // do something for 1, 2, 3 and 4
    break;
}

A realistic example (by request):

switch(typeOfPathName)
{
case "relative":
    pathName = Path.Combine(currentPath, pathName);
    goto case "absolute";

case "expand":
    pathName = Environment.ExpandEnvironmentVariables(pathName);
    goto case "absolute";

case "absolute":
    using (var file = new FileStream(pathName))
    { ... }
    break;

case "registry":
    ...
    break;
}
Zooba
  • 11,221
  • 3
  • 37
  • 40
  • 1
    That's what the sentence means, but the question is `why is this justified?` – Greg Sansom Jan 21 '11 at 06:42
  • 1
    The question was "What exactly would this 'exception' case look like". The fact that there is no alternative in C# is what justifies it. – Zooba Jan 21 '11 at 06:45
  • 1
    What would the exception case look like, not the implementation. ie `in what circumstance would you want to do this`. – Greg Sansom Jan 21 '11 at 06:49
  • 2
    "This exception case" refers to "in a switch-statement fallthrough," the use of the word "unless" indicating an exception to the general rule of "never use" that was specified before the subject, "goto." (Stop me if I'm going too fast.) – Zooba Jan 22 '11 at 00:22
8
   public enum ExitAction {
        Cancel,
        LogAndExit,
        Exit
    }

This is neater

ExitAction action = ExitAction.LogAndExit;
switch (action) {
    case ExitAction.Cancel:
        break;
    case ExitAction.LogAndExit:
        Log("Exiting");
        goto case ExitAction.Exit;
    case ExitAction.Exit:
        Quit();
        break;
}

Than this (especially if you do more work in Quit())

ExitAction action = ExitAction.LogAndExit;
switch (action) {
    case ExitAction.Cancel:
        break;
    case ExitAction.LogAndExit:
        Log("Exiting");
        Quit();
        break;
    case ExitAction.Exit:
        Quit();
        break;
}
djeeg
  • 6,685
  • 3
  • 25
  • 28
  • You can't `goto case` of enumerations - it has to be a constant. A shame really, since it would be handy, but that appears to be the behaviour. – Zooba Jan 22 '11 at 00:20
  • 10
    err, yes you can, enumerations are treated as constants – djeeg Jan 22 '11 at 00:28
  • 4
    Gah, must've mistyped something when I tested it earlier. It compiles now... I swear it didn't before. Sorry. +1 – Zooba Jan 22 '11 at 06:06
7

In addition to using goto case, you can goto a label that is in another case clause:

    switch(i) {
    case "0":
        // do some stuff
        break;
    case "1":
        // other stuff, then "fall through" to next case clause
        goto Case2;
    case "2":
    Case2:
        break;
    }

This way, you can jump to another case clause without worrying about the value or type of the expression.

Some sort of explicit "fallthrough" keyword that can be substituted for break would have been nice, though...

4

It's the only way that C# allows a switch case 'fallthrough'. In C# (unlike C, C++ , or Java), a case block in a switch statement must end with a break or some other explicit jump statement.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
3

By way of an extension to Mehrdad Afshari's advice above, I would never advocate simply exiling a construct as 'bad code' or 'bad coding practice'. Even 'goto' statements have their place in the grand scheme of things. The dogma that they are evil did not come to pass because of any inherent flaw in the construct - it was because they were heavily (and poorly) over-used.

In any case, Kernighan and Ritchie felt that allowing a case to fall through was the proper way to go. Frankly, I'm more inclined to trust their reasoning than anything that could conceivably come out of any mind in the whole of Redmond, Washington. Or any dogma that is predicated on the wisdom of any mind in Redmond.

If you ever hear 'Never use xxx', mentally append that with 'without cause'. Just tossing out anything dogmatically is ridiculous. Devices exist because there was a reason to make them. They are, in hindsight, usually referred to as 'bad' not because of any fault in the device itself, but rather because they were employed poorly by people who did not fully understand them. Thus, the device is hardly ever 'bad'. What is almost always bad is user comprehension. This is true even of atomic fission and fusion.

I've seen horrendously grotesque code structures whose sole function was to avoid the use of a 'goto' statement. What is worse? "goto [label]", or 30 lines of disgusting code whose function is to avoid having to type "goto [label]"?

Seek knowledge before dogma. Think before you act. These are useful advices.

  • True point.The funny part is that this counts for nearly everything, not just for devices. A gun for example, its not the weapon on the table that does any harm, its the person who uses it. It can also be used for good things like protecting someone that is being robbed. It ENTIRELY depends on the user. – ThrowingDwarf Mar 31 '16 at 06:52
0

I know that is old topic but question is still actual. Could we use the next code instead ugly version with goto statement ?

var variable = 2;
switch (variable)
{
case 2:
Console.WriteLine("variable is >= 2");
goto case 1;
case 1:
Console.WriteLine("variable is >= 1");
break;


}

might be substituted with the next neater code:

if (variable >= 2)
{
Console.WriteLine("variable is >= 2");
}
if (variable >= 1)
{
Console.WriteLine("variable is >= 1");
}
Oleg Bondarenko
  • 1,694
  • 1
  • 16
  • 19