• Post Reply Bookmark Topic Watch Topic
  • New Topic

K&B on labeled break  RSS feed

 
Tanmoy Dhara
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
excerpt from K & B

Remember,continue statement must be inside a loop;otherwise,you'll get a compiler error.break statements must be used inside either a loop or switch statement. (note: this does not apply to labeled break statements )


so,if i use labeled break, can i use break outside loop? how?can you give me an example?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in an if statement...

 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have to add to that.

Basically every code block (enclosed in curly braces) can contain a break statement if it refers to a label.

Note that you can have blocks without any if, while, for etc.



I use these approaches of braces mostly because of scope reasons.
 
Tanmoy Dhara
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i understand now,thank you
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16045
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that while it's useful to know that such a construct exists, please don't use it in real programs... it's a kind of disguised goto statement, which can make programs very hard to read (it's easy to create spaghetti code using goto-like statements).

Use other control flow constructs, such as for- or while-loops, instead of labels and labeled breaks.
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper Young wrote:Note that while it's useful to know that such a construct exists, please don't use it in real programs... it's a kind of disguised goto statement, which can make programs very hard to read (it's easy to create spaghetti code using goto-like statements).

Use other control flow constructs, such as for- or while-loops, instead of labels and labeled breaks.


I find it useful to use a labeled break statement from a nested loop. I mean it looks much cleaner to me than setting a boolean variable and break twice.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!