Expert C Programming

(Jeff_L) #1

makes it simpler to detect what a particular name is. Future generations will then bless your name
instead of reviling your works.


The Piece of Code that Understandeth All Parsing


You can easily write a program that parses C declarations and translates them into English. In fact,
why don't you? The basic form of a C declaration has already been described. All we need to do is
write a piece of code which understands that form and unscrambles it the same way as Figure 3-4. To
keep it simple, we'll pretty much ignore error handling, and we'll deal with structs, enums, and unions
by compressing them down to just the single word "struct", "enum" or "union". Finally, this program
expects functions to have empty parentheses (i.e., no argument lists).


Programming Challenge


Write a Program to Translate C Declarations into English


Here's the design. The main data structure is a stack, on which we store tokens that we have
read, while we are reading forward to the identifier. Then we can look at the next token to
the right by reading it, and the next token to the left by popping it off the stack. The data
structure looks like:


struct token { char type;


char string[MAXTOKENLEN]; };


/* holds tokens we read before reaching first


identifier */


struct token stack[MAXTOKENS];


/ holds the token just read /


struct token this;


The pseudo-code is:


utility routines----------


classify_string


look at the current token and


return a value of "type" "qualifier" or "identifier"


in this.type


gettoken

Free download pdf