C语言 复杂声明 dcl

将复杂声明转化为自然语言描述的程序

本程序主要借助两个相互调用的函数dlc()和dir()来读取一个复杂声明中的定义情况(例如:char (*(*x[3])())[5] ,对该声明应该是x:array[3] of point to function returning pointer to array[5] of char )。
在使用递归时,应将递归程序最里层要实现的目的为基础将函数写出来(因为递归程序必然每层的功能都一样),再考虑进入递归的条件,放入函数的适当位置。
在编写本程序时遇到枚举函数无法通过编译的情况*(/*enum { NAME, PARENS, BRACKETS } ;),如果有看官知晓原因的麻烦指出错误之处,感激不尽!

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

#define MAXTOKEN 100
#define NAME 0
#define PARENS 1
#define BRACKETS 2
/*enum { NAME, PARENS, BRACKETS } ;为什么这段声明过不了编译(error C2143: 语法错误 : 缺少“;”(在“}”的前面))*/

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';/*每一行都应该将out清空*/
		dcl();
		if(tokentype != '\n')
			printf("synatax error\n");
		printf("%s:%s %s",name,out,datatype);
	}
	return 0;
}

int gettoken(void)
{
	int getch(void);
	void ungetch(int);
	int c;
	char *p = token;

	while((c = getch()) == ' ' || c == '\t')
		;
	if(c == '('){
		if((c = getch()) == ')'){
			strcpy(token,"()");
			return tokentype = PARENS; /*这里return的用法要注意*/
		}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;/*这里的c有可能是'\n'、'EOF'、')'和非法字符*/
}

#define BUFFSIZE 1000

int buffer[BUFFSIZE];
int buffp = 0;

int getch(void)
{
	return (buffp > 0) ? buffer[--buffp] : getchar();
}

void ungetch(int c)
{
	if (buffp >= BUFFSIZE)
		printf("ungetch:too many characters\n");
	else
		buffer[buffp++] = c;
}

void dcl(void)
{
	int n;

	for(n = 0;gettoken() == '*'; )
		n++;
	dirdcl();
	while(n-- > 0)
		strcat(out," pointer to");/*由里层逐渐向外层添加*/
}

void dirdcl(void)
{
	int type;

	if(tokentype == '('){ /*又是另一个dcl*/
		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()) == BRACKETS || type == PARENS)
	{
		if(type == PARENS)
			strcat(out," function returning");
		else{
			strcat(out," array");
			strcat(out,token);
			strcat(out," of");
		}
	}
}`
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值