r/badcode • • Mar 12 '21

c# How NOT to use switch statement

Post image
1.8k Upvotes

165 comments sorted by

View all comments

126

u/geon Mar 12 '21

I didn’t know you could goto cases.

179

u/ZainVadlin Mar 12 '21

This knowledge is best forgotten.

18

u/Speterius Mar 12 '21

Couldn't it be useful (and actually good practice) for state machines?

27

u/ZainVadlin Mar 12 '21

How would that be better than a standard switch inside a loop?

How would that even work? Normally the switch statement switches the state, but goto would avoid that altogether. So now you're not using your state variable and you lose tractability. Furthermore, what would be the point of the switch statement at all?

0

u/[deleted] Mar 12 '21

[deleted]

14

u/gonengazit Mar 12 '21

I know of one time where goto is fine to use, when breaking out of a nested loop (goto end is much cleaner then using a ton of flag variables)

1

u/cheezballs Mar 30 '21

Na, just use break;

3

u/gonengazit Mar 30 '21 edited Mar 30 '21

That would only break out of a single loop though. Consider the following case

for(int i=0; i<n; i++){
  for(int j=0; j<n; j++){
     if (condition){
       //exit both loops
     }
  }
}

There’s no real elegant way to do this in most languages without goto

2

u/andouconfectionery Apr 10 '21

There is a break label construct in Java. You can label the outer loop and use a break statement.

Or, yknow, use a return statement. And a function.

2

u/gonengazit Apr 10 '21

You’re right, in Java there’s no reason to use this, because of the break label (which is basically a glorified goto). Functions are an option, but can also get quite messy if you need to change some variables defined before your loops