I've been stuck with the dcl program from chapter 5.12 in K&R C. It is basically a program which accepts a C variable/function/table declaration and prints a description of it in English. It works for simple declarations such as int a but fails with more complicated ones. For example, when I enter int (*pf)() I get the output
error: expected name or (dcl)
Syntax error
: int
error: expected name or (dcl)
: function that returns pf
Below is the portion of the code related to the program. The getch() and ungetch() functions are in a separate file.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "getch.h"
#define MAXTOKEN 100
enum { NAME, PARENS, BRACKETS };
void dcl(void);
void dirdcl(void);
int gettoken(void);
int tokentype;
char token[MAXTOKEN];
char name[MAXTOKEN];
char datatype[MAXTOKEN];
char out[1000];
int main(void)
{
while (gettoken() != EOF) {
strcpy(datatype, token);
out[0] = '\0';
dcl();
if (tokentype != '\n')
printf("Syntax error\n");
printf("%s: %s %s\n", name, out, datatype);
}
return 0;
}
void dcl(void)
{
int ns;
for (ns = 0; gettoken() == '*'; )
ns++;
dirdcl();
while (ns-- > 0)
strcat(out, " pointer to");
}
void dirdcl(void)
{
int type;
if (tokentype == '(') {
dcl();
if (tokentype != ')')
printf("error: missing )\n");
} else if (tokentype == NAME)
strcpy(name, token);
else
printf("error: expected name or (dcl)\n");
while ((type=gettoken()) == PARENS || type == BRACKETS) {
if (type == PARENS)
strcat(out, " function that returns");
else {
strcat(out, " array");
strcat(out, token);
strcat(out, " of");
}
}
}
int gettoken(void)
{
int c;
char *p = token;
while ((c = getch()) == ' ' || c == '\t')
;
if (c == '(') {
if ((c = getch()) == ')') {
strcpy(token, "()");
return tokentype = PARENS;
} else {
ungetch(c);
return tokentype = ')';
}
} else if (c == '[') {
for (*p++ = c; (*p++ = getch()) != ']'; )
;
*p = '\0';
return tokentype = BRACKETS;
} else if (isalpha(c)) {
for (*p++ = c; isalnum(c = getch()); )
*p++ = c;
*p = '\0';
ungetch(c);
return tokentype = NAME;
} else
return tokentype = c;
}
Could you please help me pinpoint the mistake?
return tokentype = ')';ingettoken()looks wrong. It should probably bereturn tokentype = '(';, instead. There may be other issues.return tokentype = ')📍';.