4 ms·
Java actually has an elegant-for-Java feature that removes most credible uses of goto. You can label and break out of standalone code blocks. It makes error han
by dehrmann 5y ago
Java actually has an elegant-for-Java feature that removes most credible uses of goto. You can label and break out of standalone code blocks. It makes error handling without exceptions no bad.
label: {
break label;
}
- abnercoimbre 5y agoOh my goodness! I'm using this right away (yesterday I was lamenting lack of goto for this exact use case.) This is just Java, right? I don't think I've seen this in the C/C++ specs or compiler extensions.
- superdisk 5y agoWell if you're using C, you could just use a proper goto.
- jcranmer 5y agoLabeled break/continue are present in most languages that postdate Java. Go, JavaScript, Kotlin, Nim, Rust, Zig, for example, all have labeled break/continue as well. The only notable post-Java language I'm aware of that doesn't have it is C#. Languages that predate Java generally don't have such a feature--and this includes C/C++.
- aurelianito 5y agoYou can have the same flow in python raising and catching an exception.
- nerdponx 5y agoDoesn't Perl also have this? It would be a great feature in Python, although I wouldn't use it very often.
- gnubison 5y agoIn Perl, any “bare block” is equivalent to a loop that only runs once. Useful in conjunction with redo too.
- nielsbot 5y agoSwift also has (copied?) this... https://docs.swift.org/swift-book/ReferenceManual/Statements.html#ID441 https://docs.swift.org/swift-book/ReferenceManual/Statements... (And I always forget about it)
- chrismorgan 5y agoAnd in most C-style languages that don’t have labelled blocks like this, you can use an infinite loop to achieve the same effect; for example, in Rust where labelled blocks aren’t yet stable: 'label: loop { break 'label; } And if you want to go one further on that, you can break with value because Rust is expression-oriented: fn main() { println!("Hello, {}!", 'label: loop { break 'label "world"; }); }