Hi,

I have a homework to do for college, which asks me to write a pascal lexical analizer in C. I'm trying to figure out the best way to ignore the comments, so far I've written this code, which works, but I would like to know if there is an simpler way to do that, here is my code:

   input = fopen("./arquivo.pas", "r");

   while ((c = fgetc(input)) != EOF)
   {
      if (c == '{')
      {

         do
         {
           c = fgetc(input);
         }
         while (c != '}');

         continue;

      } else if (c == '/')
      {
         if (( c = fgetc(input) == '/'))
           do{}while((c = fgetc(input)) != '\n'); 
        else
        {
           printf("/");

           fseek(input, -1, SEEK_CUR);

           continue;
        }

      }

      printf("%c", c);
   }

Regards.

delete lines 14 and 26, the continhue statement is not needed

not needed lines 14 and 26, delete pls

Till this, it will work fine. In lexical analyzer you are required to create parse tree for semantic checkings. You may want to refer to a book "Compilers Principals Techniques and tools" by Aho, Ullman, Sethi.

A couple other things worth noting:

1: do{}while((c = fgetc(input)) != '\n');
Why a do-while? Why not just while((c = fgetc(input)) != '\n');??

2: fseek(input, -1, SEEK_CUR);
Why? Can't you do something better/cleaner than messing with the file pointer?
It looks like you're already handling the case without the fseek().

3: printf("%c", c);
This is a very expensive statement to use for character output. It's much cleaner to use putchar().

Why? Can't you do something better/cleaner than messing with the file pointer?

There is where I'm getting confused with the logic, if the character is a slash, and the next character is not a slash, I need to treat that character, as it is not a comment. Any suggestion?

thanks.

What would you do with the character if you read an 'A'? Do that with the '/' in the else then continue as normal since c now contains the next character.

read char
if '/'
    read char
    if '/' ignore rest of line
    if not '/' do your stuff with '/'
do your stuff with char

Hi,

I'll try to improve this code, Thanks to everyone who gave me suggestions.

Regards.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.