0
$\begingroup$

Given the programming language C#, how would I be able to write the BNF and EBNF grammar syntax of its while loop?

After trying to search and understand more, I got this as my BNF grammar for while loops

< while-statement > :: = < do-statement >< while-statement > | < do-statement >

though I don't think it's quite right

$\endgroup$
1

1 Answer 1

1
$\begingroup$

The common element in "while statements" and "do statements" is the continuation condition, which is an expression inside parentheses, always indicated with the keyword while. If you wanted to, you could capture this commonality with something like:

<while-clause> ::= "while" "(" <expression> ")"
<while-statement> ::= <while-clause> <embedded-statement>
<do-statement> ::= "do" <embedded-statement> <while-clause> ";"

I'm not sure whether that adds any readability to the grammar. The actual C# grammar doesn't bother; it just uses

<while-statement> ::= "while" "(" <expression> ")" <embedded-statement>
<do-statement> ::= "do" <embedded-statement> "while" "(" <expression> ")" ";"

Thanks to @JörgWMittag for the above link, in which you have to search for while_statement because the productions aren't tagged. Also see the specification text.

Either way, the productions simply reflect the evident syntax. At a high level, you can get surprisingly far into the writing of a grammar by just explaining the construct in your own language. ("A while statement starts with the keyword while, followed by the continuation expression surrounded by parentheses, and then the statement to be iterated.")

The only subtlety here is the use of <embedded-statement> instead of, say, <statement>. That's because C#, like C and other C-derivatives, doesn't permit embedded statements to be declarations or to have labels. (If you want to do that, you'd need to embed a "block" (that is, a list of statements inside {}).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.