Chinaunix首页 | 论坛 | 博客
  • 博客访问: 47358
  • 博文数量: 33
  • 博客积分: 1301
  • 博客等级: 中尉
  • 技术积分: 335
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-31 21:06
文章分类
文章存档

2009年(33)

我的朋友

分类: C/C++

2009-06-18 18:57:55

 
 
5.12 Complicated Declarations
The C Programming Language
 
超级经典又有诠释力的例子:dcl.c
 
重点要掌握的是 dcl()和 dirdcl() 的交互,然后是gettoken()
 

#include <stdio.h>
#include <string.h>
#include <ctype.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()
{
  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;
}

int gettoken(void)
{
  int c;
  char *p = token;
  
  while ((c = getchar()) == ' ' || c == '\t')
    ;
  if(c == '(') {
    if((c = getchar()) == ')') {
      strcpy(token, "()");
      return tokentype = PARENS;
    } else {
      ungetc(c, stdin);
      return tokentype = '(';
    }
  } else if (c == '[') {
    for(*p++ = c; (*p++ = getchar()) != ']'; )
      ;
    *p = '\0';
    return tokentype = BRACKETS;
  } else if (isalpha(c)) {
    for(*p++ = c; isalnum(c = getchar()); )
      *p++ = c;
    *p = '\0';
    ungetc(c, stdin);
    return tokentype = NAME;
  } else {
    return tokentype = c;
  }
}

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 of (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");
    }
}

 
阅读(298) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~