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

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