Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Unreachable label  RSS feed

 
Daniel Cox
Ranch Hand
Posts: 231
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does this code compile even though the start: label is unreachable. I say that it is unreachable because you will never be able to write break start or continue start

 
Tim Cooke
Marshal
Posts: 3872
233
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The line with the 'start' label is reachable. The console output prints "start" proving the case.

It is not compulsory to reference labels:
 
Daniel Cox
Ranch Hand
Posts: 231
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never mind. After doing some googling, I found out that any Java statement (except a declaration) can be labelled. I guess it provides an alternative way to comment your code. However, the most common use of labels is their use in break and continue statements.

Tim Cooke wrote:The line with the 'start' label is reachable.

I meant that the start: label can never be reached by a break or continue statement.
 
Carey Brown
Bartender
Posts: 2996
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Daniel Cox wrote:Never mind. After doing some googling, I found out that any Java statement (except a declaration) can be labelled. I guess it provides an alternative way to comment your code. However, the most common use of labels is their use in break and continue statements.

Do not use labels to comment your code, the comment syntax (//) (/**/) is much better for doing that.

Yes, labels can be combined with break and continue statements, but only use them when trying to break out of nested loops and switches. Some would argue that even using labels in this way, while syntactically correct, is equivalent to the frowned upon GOTO, and that alternatives should be used instead.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!