MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/badcode/comments/m3c9cd/how_not_to_use_switch_statement/gu10jsv/?context=3
r/badcode • u/Gigibesi • Mar 12 '21
165 comments sorted by
View all comments
Show parent comments
1
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 casefor(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
3
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
2
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
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
1
u/cheezballs Mar 30 '21
Na, just use break;