Page 1 of 1

break's scope

Posted: 10 May 2009 17:28
by jacky
I know I'm late to the party, as it has already been included on a new official release, but I have a question about break. It seems that the way it was done, break works for while as well as if, and I was just wondering if that was such a good idea.

Might be that I'm used to PHP (where break doesn't apply to if's) but I find this somewhat odd:

Code: Select all

  $i = 3;
  while (1)
  {
   $i--;
   if ($i == 0) { break 2; }
  }
And I probably find it even more odd that if I had only used "break;" it only applied to the if, and so this was an endless loop...

Besides, maybe I'm not seeing the obvious, but why would you ever break from a if? Isn't it the same/easier to just close the bracket?

Any reason this was done that way, and not like PHP does it? Any other opinions as to which is better?

Re: break's scope

Posted: 10 May 2009 21:09
by admin
Hmm, I see your point. Really looks odd. Frankly I did not think much when I did it. It was possible to do it for both IF and WHILE with one piece of code, so I thought "why not?"

Other opinions?

Re: break's scope

Posted: 10 May 2009 21:52
by PeterH
Sorry, but what would you break in an IF?

Re: break's scope

Posted: 10 May 2009 22:04
by admin
PeterH wrote:Sorry, but what would you break in an IF?
Okay, break 1 is meaningless, but break 2 or break 3 etc. could make sense maybe:

Code: Select all

if (a) {
  if (b) {
    if (c) {
      break 2;  //continues with code f
    }
    elseif (d) {
      break 3;  //continues with code g
    }
    ... code e
  }
  ... code f
}
... code g
Just to be sure: I'm not inclined to leave it the way it is because it is weird and certrainly non-standard (see jacky's examples) -- I'm just asking if there might be any use for it...

Re: break's scope

Posted: 10 May 2009 22:13
by PeterH
Ouuuu :shock:

Formally seems correct.
But I don't think I would like that programming style :roll:

Re: break's scope

Posted: 11 May 2009 03:30
by mwb1100
FWIW C/C++ break only has effect for the "do", "for", "while" and "switch" statements. I think that makes sense.

However, C/C++ do not have the capability to specify that a break exit out of more than one level, which I think is a nice feature to have. Every once in a while in a program I will miss having that capability and have to jump through some hoops to work around it.