Syntax diagrams
Syntax diagrams
Another way of representing the syntax of keywords, instructions and the elements of a programming language is to use syntax diagrams. These are possibly more straightforward to understand than BNF notation. They are very useful to the programmer because they can be used to ensure that the correct syntax of instructions and declarations, for example, are used.
Consider the BNF definition of a signed integer. This is an unsigned integer with either a plus or a minus in front of it. There are different ways of solving this but one way is as follows:

A signed integer could also be represented using a syntax diagram. Again, there are different ways of representing the same logic. Here is one way, using 2 diagrams.

How do you read a syntax diagram?
Always start reading the diagram from the left and follow the flow to the right! You cannot go back on yourself unless there is an arrow that lets you! The first diagram defines a digit. Starting from the left, you can flow to the right through only one of a number of paths, and then out again. So, for example, you may flow through the digit 7 and then out again. You cannot backtrack because there isn’t an arrow to take you back. Thus, a digit is made up of only one number.
The second diagram again must be read from left to right. You have a choice how a signed integer can begin, either with a plus or a minus sign. Then it needs a digit. From the definition in the first diagram, a digit is made up of one symbol. After one symbol has been selected, the signed integer can finish, or it can loop back on itself (because there is an arrow that lets it do this) and collect another digit, and so on, until the signed integer is finished.
Terminal symbols and rectangular boxes
Some further points to note. Some symbols are in circles, like 0, 1, 2, + and so on. These are terminal symbols and cannot be broken down further by reference to other syntax diagrams. Other symbols such as digit are in a rectangular box. That means that you need to refer to another syntax diagram to get the full definition. This ensures that complicated syntax diagrams can be produced which aren’t too cluttered.
IF – THEN – ELSE example
In the programming language Pascal, you could use an IF construction in the following way:
IF score >= 80 then
writeln(‘Pass with honours’)
or you might use an ELSE in the code, like this:
IF score >= 70 then
writeln(‘Pass with honours’)
ELSE
IF score >= 60 then
writeln(‘Pass’)
ELSE
writeln(‘Fail’);
{ENDIF}
{ENDIF}
We can show the syntax diagram for an IF statement or IF – THEN – ELSE statement like this:
‘Expression’ and ‘Statement’ are in rectangular boxes so they have their own definition, which we would need to refer to. IF, THEN and ELSE cannot be broken down any further so they are shown in circles.