I took me a while to check since I first had to find a grammar file for C#, but it is definitely a semantic error. The grammar specifies what are valid constructs in a language. If the written program follows the grammar then it is syntactically correct.
I'll only post the relevant parts of the grammar that will make it clear why a break
anywhere in a C# program is syntactically correct, but is semantically wrong here in the sense of "There is nothing to break out of, so it does not make sense to break here.".
Excerpt of C# grammar file:
block:
';'
| '{' statement_list? '}';
statement_list:
statement+ ;
statement:
(declaration_statement) => declaration_statement
| (identifier ':') => labeled_statement
| embedded_statement
;
embedded_statement:
block
| selection_statement // if, switch
| iteration_statement // while, do, for, foreach
| jump_statement // break, continue, goto, return, throw
| try_statement
| checked_statement
| unchecked_statement
| lock_statement
| using_statement
| yield_statement
| unsafe_statement
| fixed_statement
| expression_statement // expression!
;
jump_statement:
break_statement
| continue_statement
| goto_statement
| return_statement
| throw_statement ;
break_statement:
'break' ';' ;
The chain is:
block -> statement_list -> statment -> embedded_statement -> jump_statement -> break_statement -> "break"
From the grammar file we can infer that the break statement would be
allowed anywhere inside a block. Thus programs that have a break statement that is
not within a looping construct or a switch statement are still
syntactically correct. The compiler has enough cleverness built in though to see that the break statement which is not enclosed in the aforementioned statements does not make any sense and throws a compile time error.
The error is a semantic error because the grammar allows for break statements to appear anywhere inside a block ({})
I hope I explained it well enough, if you still have questions leave me a comment.
[Update]
Forgot the link where to find said grammar file. On this site there is a download of a zip file:
http://antlrcsharp.codeplex.com/[
^]. In the folder UnitTest there is a file called
cs.g
which contains the complete grammar.
[/Update]
Regards,
—MRB