K & R C Programs Exercise 5-18.

K and R C, Solution to Exercise 5-18:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program to convert the C declaration into a word description and Make dcl recover from input errors.Read more about C Programming Language .

* You can use all the programs on www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact [email protected]
* To find more C programs, do visit www.c-program-example.com
* and browse!
* Happy Coding

enum { NO, YES};
void dcl(void);
void dirdcl(void);
void errmsg(char *);

int gettoken(void);
extern int tokentype;
extern char token[];
extern char name[];
extern char out[];
extern int prevtoken;

int type;
char temp[MAXTOKEN];
while (gettoken() !=EOF) {
strcy(out, token);
while ((type = gettoken()) != 'n')
if(type == PARENS || type == BRACKETS)
strcat(out, token);
else if(type == '*') {
sprintf(temp, "(*%s)", out);
strcpy(out, temp);
}else if(type == NAME){
sprintf(temp, "%s%s",token, out);
strcpy(out, temp);
printf("Invalid input at %sn",token);
return 0;

//dcl:parse a declarator
void dcl(void)
int ns;
for(ns = 0; gettoken() == '*';)
while(ns --> 0)
strcat(out, "pointer to");

//dirdcl: parse a direct declaration
void dirdcl(void)
int type;
if(tokentype == '('){
if(tokentype != ')')
else if(tokentype == NAME)
errmsg("error:expected name or (dcl)n");
while((type = gettoken()) == PARENS || type == BRACKETS)
if(type == PARENS)
strcat(out, "function returning");
else {
strcat(out, "array");
strcat(out, token);
strcat(out, "of");

//errmsg: prints the error message
void errmsg(char *msg)
prevtoken = YES;

//get token:return next token
int gettoken(void)
int c, getch(void);
void ungetch(int);
char *p = token;
if(prevtoken == YES) {
prevtoken = NO;
return tokentype;
while((c = getch()) == ' ' || c == 't')
if(c == '('){
if ((c = getch()) == ')'){
return tokentype = PARENS;
return tokentype = '(';
else if(c == '['){
for(*p++ = c; (*p++ = getch()) != ']';)
*p = '';
return tokentype = BRACKETS;
else if (isalpha(c)) {
for(*p++ = c; isalnum(c = getch());)
*p++ = c;
*p = '';
return tokentype = NAME;
} else
return tokentype = c;

Read more c programs
C Basic
C Strings
K and R C Programs Exercise

You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can Follow @c_program

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it

(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this link
(c) www.c-program-example.com

Leave a Reply