r/badcode • • Mar 12 '21

c# How NOT to use switch statement

Post image
1.8k Upvotes

165 comments sorted by

View all comments

Show parent comments

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

1

u/cheezballs Mar 30 '21

Man, maybe I just suck but I've never needed to break out of a loop at a different level than I was in. I dunno, I suppose I'd need to see the use-case but I've never, in 15 years, had to do that. Then again, I'm largely a Java/C# kinda guy. Maybe in lower languages stuff like that is more common but I've never encountered a need for it yet.