Sep 5, 2016

K & R : Exercise 1.24 - Rudimentary C syntax checker

K & R : Exercise 1.24 - Rudimentary C syntax checker

Problem

Write a program to check a C program for rudimentary syntax errors like unbalanced parenthesis brackets and braces. Don't forget about quotes both single and double, escape sequence and comments. (This program is hard, if you do it in full generality).


Solution

First and for most important thing is that it has to simple. We are not writing a C compiler here. Lets stick to simpleness rather than completeness.

First thing is balancing a brackets, We could increment counter for every ( and decrement for every ). In the end if the count is 0 then the brackets are balanced. This is not exactly correct (correct implementation would need a stack) but very simple. Same could be extended to {, [. Every comment /* should end with */. Lets put all these things into C Program.

#include <stdio.h>
int main()
{
  int ch = 0, pch = 0;
  int round_count = 0;
  int square_count = 0;
  int flower_count = 0;
  int comment_count = 0;

  while((ch = getchar()) != EOF) {
    if(ch == '(') {
      round_count++;
    }else if(ch == '[') {
      square_count++;
    }else if(ch == '{') {
      flower_count++;
    }else if(ch == '*' && pch == '/') {
      comment_count++;
    }else if(ch == ')') {
      round_count--;
    }else if(ch == ']') {
      square_count--;
    }else if(ch == '}') {
      flower_count--;
    }else if(ch == '/' && pch == '*') {
      comment_count--;
    }
    pch = ch;
  }
  if(round_count != 0) {
    printf("Syntax Error: Unbalanced Round brackets\n");
  }
  if(square_count != 0) {
    printf("Syntax Error: Unbalanced Square brackets\n");
  }
  if(flower_count != 0) {
    printf("Syntax Error: Unbalanced Flower brackets\n");
  }
  if(comment_count != 0) {
    printf("Syntax Error: Unbalanced Comment\n");
  }
  return 0;
}

No comments :

Post a Comment