Reputation: 23
Write a simple BNF grammar for a subset of C that supports multiple statements including assignment, if-else, and while statements without block statements. Use meaningful names for your nonterminals (vs. cryptic letters). Assume variables are represented by single letters and are integers. Assume that the standard precedence rules apply for the operators *, /, +, -, and parentheses. Make sure to include relational operators (==, !=, <, >, >=, and <=). The following is a valid program for your grammar:
a = -35;while (b > a);a = a + b;if (a >= 10);c = a;else c = b;
Can you expand your BNF to properly handle a C block statement as part of a while or if or else? Revise your productions to support: while (b > a) a = a + b; printf(“in loop”);
using the above grammar I came up with
<statement> ::= a=-35
<while> ::= while (b>a)
<assign>::= a = a + b;
<if>::= if (a >= 10)
<assign> ::= c=a;
<else>
<assign> ::= c = b;
<while>::= while (b>a)
<assign>:= a = a + b;
<statement>::= printf ("in loop");
Is this a valid bnf grammar ?
Upvotes: 0
Views: 8346
Reputation: 24895
No. What you are writting are more examples than a grammar. A grammar explains how to produce all the valid constructs of the language.
For example
<while> ::= while <expression> <block>
Then, you define <expression>
in a way that allows to write any expression in the language, and <block>
as a block of statements (a simple statement or several statement grouped by brackets).
http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form
Upvotes: 5