Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Flow Control : Labels

 
kumar bangali
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
This clarification is regarding the use of labels in flow control. I was under the impression that labels could be used to pass control to any statement and not necessarily to the start of the loop alone. But in the following examples the code does not compile in (1) and (2) but compiles fine in (3)
(1)

2

3

Thanx in advance
 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you cannot forward reference a label, it must be declared before it is used with continue or break, also the label tag must immediatly proceed the enclosed statement.
the code example below will not compile since the label "here:" does not immediatly proceed the for block

here:
int j=0;
for(int i=0; i<10; ++i) {
if(i==5) break here;
}
if you swap here: and int j=0; then the code will compile
 
mark stone
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you could do such a thing in C language. basically java does not have a goto statement.
because break and continue are nothing but transfer of control, just like goto in procedural languages.
In java break and continue are to be used with
for, while and do-while loops. And second the labels have to just before where the for,while statements are. You cannot place your labels anywhere you want.

Originally posted by kumar bangali:
Hi
This clarification is regarding the use of labels in flow control. I was under the impression that labels could be used to pass control to any statement and not necessarily to the start of the loop alone. But in the following examples the code does not compile in (1) and (2) but compiles fine in (3)
(1)

2

3

Thanx in advance
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic