----------
import std.stdio;
void main() {
block: {
for (int i = 0; i < 10; i++) {
if (i == 5) break block;
}
writefln("Within block");
}
writefln("Outside block");
}
----------
Within block
Outside block
----------
I was expecting it to print only "Outside block". However, according to the spec, the code shouldn't compile:
http://www.digitalmars.com/d/statement.html
"If break is followed by Identifier, the Identifier must be the label of an enclosing while, for, do or switch statement, and that statement is exited. It is an error if there is no such statement."
The restriction to while, for, do or switch seems arbitrary, but still....
It works as spec'd, and you're right it is the same issue as 199. Won't change behavior for the same reason. Note that if you write it as (inserting an if statement):
import std.stdio;
void main() {
block: if (1) {
for (int i = 0; i < 10; i++) {
if (i == 5) break block;
}
writefln("Within block");
}
writefln("Outside block");
}
it won't compile per the spec.
Comment #3 by smjg — 2008-06-23T18:04:30Z
(In reply to comment #2)
> It works as spec'd,
No it doesn't. The statement from the spec that I already quoted is still there, word for word.
> and you're right it is the same issue as 199.
Maybe within the compiler, but not insofar as according to the language, the label is of the BlockStatement not of the ForStatement therein. What the label labels and whether the BlockStatement opens a new scope or not are essentially distinct concepts.
> Won't change behavior for the same reason.
If you're referring to bug 199 comment 6, neither point seems to me to apply here:
> I don't want to change this because it could break existing code,
Somebody who wants the existing behaviour of my code example can just use
void main() {
block: for (int i = 0; i < 10; i++) {
if (i == 5) break block;
}
writefln("Within block");
writefln("Outside block");
}
so what's there to break?
> and there doesn't seem to be a compelling reason to do so.
I certainly think there is: the nasty shock a programmer gets on trying this code, expecting it to (a) be legal (b) if so, behave in a way that makes intuitive sense.
(In reply to comment #2)
> Note that if you write it as (inserting an if statement):
<snip>
> it won't compile per the spec.
Maybe. But is this really relevant? Nobody's going to do this just to make the compiler catch the error, since doing so would imply that the coder's own eyes have already caught the error.
Comment #4 by nick — 2017-10-23T15:13:40Z
(In reply to Stewart Gordon from comment #0)
> ----------
> block: {
> for (int i = 0; i < 10; i++) {
> if (i == 5) break block;
> }
dmd 2.076.1 (dpaste) now gives:
/d220/f421.d(7): Error: label `block` has no break
Comment #5 by razvan.nitu1305 — 2019-05-23T11:26:58Z
The code in the original bug report now errors in D2. Closing as WORKSFORME.