Exercise 1-24 (Syntax checker)
Chapter_1 Exercise_1-23 | ch1-Exercises Chapter_2 |
Exercise 1-24 K&R, p. 34
Write a program to check a C program for rudimentary syntax errors like unbalanced parentheses, brackets and braces. Don't forget about quotes, both single and double, escape sequences, and comments. (This program is hard if you do it in full generality.)
Note: First we remove the comments from a C file with nocomment from Exercise_1-23, then we use the program checker below.
checker.c download
#include <stdio.h> // for getchar(), printf(), EOF
int main()
{
int c;
int leftPar = 0, rightPar = 0;
int leftBrackets = 0, rightBrackets = 0;
int leftBraces = 0, rightBraces = 0;
while ((c = getchar()) != EOF)
{
if (c == '\\') // escape character or sequence
{
c = getchar();
if (c == EOF || c == '\n')
{
printf("\nEscape character not ended properly\n"); // Error message
return 1; // return from main(), end program with an error message
}
}
else if (c == '\'') // character
{
while ((c = getchar()) != '\'')
{
if (c == EOF || c == '\n')
{
printf("\nEscape character not ended properly\n"); // Error message
return 1; // end program with an error message
}
else if (c == '\\') // escape char or sequence
{
c = getchar();
if (c == EOF || c == '\n')
{
printf("\nEscape character not ended properly\n"); // Error message
return 1; // end program with an error message
}
}
} // here c == '\''
}
else if (c == '\"') // strings are on a single line
{ // Skip strings: "/*" "*/" "//" "'" "\"\'"
while ((c = getchar()) != '\"')
{
if (c == EOF || c == '\n')
{
printf("\nQuoted string not ended properly\n"); // Error message
return 1; // end program with an error message
}
else if (c == '\\') // escape char or sequence
{
c = getchar();
if (c == EOF || c == '\n')
{
printf("\nEscape character not ended properly\n"); // Error message
return 1; // end program with an error message
}
}
} // here c == '\"'
}
else if (c == '(') {leftPar++;}
else if (c == ')') {rightPar++;}
else if (c == '[') {leftBrackets++;}
else if (c == ']') {rightBrackets++;}
else if (c == '{') {leftBraces++;}
else if (c == '}') {rightBraces++;}
}
if (leftPar != rightPar)
{printf("Mismatching parentheses\n");}
if (leftBrackets != rightBrackets)
{printf("Mismatching brackets\n");}
if (leftBraces != rightBraces)
{printf("Mismatching braces\n");}
return 0;
}
/*
gcc checker.c -o checker
./nocomment < checker.c > copy.c // remove comments
./checker < copy.c // check syntax
rm copy.c // clean
*/
Chapter_1 Exercise_1-23 | BACK_TO_TOP | ch1-Exercises Chapter_2 |
Comments
Post a Comment