dud3 dud3 - 1 month ago 10
C Question

K&R - Recursive descent parser - strcat

What would be the reason for

out[0] = '\0';
on the
main()
function?

It does seem to be working without it.

Code

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAXTOKEN 100
enum { NAME, PARENS, BRACKETS };

int tokentype;
char token[MAXTOKEN]; /*last token string */
char name[MAXTOKEN]; /*identifier name */
char datatype[MAXTOKEN]; /*data type = char, int, etc. */
char out[1000];

void dcl(void);
void dirdcl(void);
int gettoken(void);

/*
Grammar:

dcl: optional * direct-dcl
direct-dcl: name
(dcl)
direct-dcl()
direct-dcl[optional size]
*/

int main() /* convert declaration to words */
{
while (gettoken() != EOF) { /* 1st token on line */

/* 1. gettoken() gets the datatype from the token */
strcpy(datatype, token);

/* 2. Init out to end of the line? */
/* out[0] = '\0'; */

/* parse rest of line */
dcl();

if (tokentype != '\n')
printf("syntax error\n");

printf("%s: %s %s\n", name, out, datatype);
}

return 0;
}

int gettoken(void) /* return next token */
{
int c, getch(void);
void ungetch(int);
char *p = token;

/* Skip blank spaces and tabs */
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)) {

/* Reads the next character of input */
for (*p++ = c; isalnum(c = getch()); ) {
*p++ = c;
}

*p = '\0';
ungetch(c); /* Get back the space, tab */

return tokentype = NAME;

} else
return tokentype = c;
}

/* dcl: parse a declarator */
void dcl(void)
{
int ns;

for (ns = 0; gettoken() == '*'; ) /* count *'s */
ns++;

dirdcl();

while (ns-- > 0)
strcat(out, " pointer to");
}

/* dirdcl: parse a direct declarator */
void dirdcl(void)
{
int type;

if (tokentype == '(') {

dcl();

if (tokentype != ')')
printf("error: missing )\n");

}
else if (tokentype == NAME) /* variable name */ {
strcpy(name, token);
printf("token: %s\n", token);
}
else
printf("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");
}

}
}

Answer

You need out[0] to be zero in order for strcat to work.

While this line

out[0] = '\0';

was required prior to the introduction of static initialization rules, it is no longer required, because static arrays, such as out[], are initialized to all zeros.

According to initialization rules of C99,

  • ...
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero.
  • if it is an aggregate, every member is initialized (recursively) according to these rules.