Got it! This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
Here a Python program is presented to show how to convert a C program fragment to an equivalent C program without curly braces blocks but with goto statements and ifgoto statements and labels.
A certain style is assumed but other styles can be handled by appropriately adjusting the Python code.
Note that the else if and else are not handled but left as exercises, as is the dowhile.
3. C code
Here is some C code what has while and if statements.
i = 0;
while ( i != n ) {
i = i+1;
j = i;
k = i;
while ( k != n ) {
k = k+1;
if ( a[k] < a[j] ) {
j = k;
}
}
swap(a[i-1], a[j]);
}
Here are the C code statements encoded as a Python list.
4. Python regular expression
The Python regular expression recognizes the while and if statements used in C (and assumes that white space on either side has been removed).
5. Routine variables
The initialization needs
a new line list to return called lineList2,
a stack called stackList1 to keep track of the nested statement blocks (i.e., while or if and the needed labels), and
the label position labelPos1 used to get the next label.
6. For each line
For each line line1, the white space on either side is removed using strip. Blank lines are ignored. If the line is and ending brace "}", the stack is popped. For an if the target label is generated. For a while the ending goto is generated an the label for the end of the while generated.
7. Match
If the line line1 matches a if or a while, the type is put into key1 and the expression text into expr1. If an if the target label is obtained, the ifgoto for the negated expression is generated, and the key1 and label1 pushed onto the stack. If a while, the label1 and label2 are generated. The label1 is generated, the ifgoto to label2 is generated using the negated expr1 and the key1 and label1 and label2 are pushed on the stack.
8. Catch-all
If the C line1 is not empty, not an ending curly brace and not a match for an if or a while statement, the line is formatted to be indented one tab stop.
The continue statements in the other code in the loop avoid the ending output since that output has already been handled (or is not needed in the case of an empty line).
9. Main code
The main code outputs the C code in the list, gets the list for the goto code, and then outputs that list.
Exercise: Add a routine to print a list as text and then call with each list instead of repeating the code.
Note: One can also abstract the "begin" and "end" text by passing another parameter.
Here is the complete program.