break's scope

Please check the FAQ (https://www.xyplorer.com/faq.php) before posting a question...
Post Reply
jacky
XYwiki Master
Posts: 3106
Joined: 23 Aug 2005 22:25
Location: France
Contact:

break's scope

Post 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?
Proud XYplorer Fanatic

admin
Site Admin
Posts: 66305
Joined: 22 May 2004 16:48
Location: Win8.1, Win10, Win11, all @100%
Contact:

Re: break's scope

Post 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?

PeterH
Posts: 2827
Joined: 21 Nov 2005 20:39
Location: DE W11Pro 24H2, 1920*1200*100% 3840*2160*150%

Re: break's scope

Post by PeterH »

Sorry, but what would you break in an IF?

admin
Site Admin
Posts: 66305
Joined: 22 May 2004 16:48
Location: Win8.1, Win10, Win11, all @100%
Contact:

Re: break's scope

Post 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...

PeterH
Posts: 2827
Joined: 21 Nov 2005 20:39
Location: DE W11Pro 24H2, 1920*1200*100% 3840*2160*150%

Re: break's scope

Post by PeterH »

Ouuuu :shock:

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

mwb1100
Posts: 213
Joined: 19 May 2007 06:20

Re: break's scope

Post 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.

Post Reply