我的c\c++之旅(十一)——声明器

来源:互联网 发布:mac照片导入 编辑:程序博客网 时间:2024/05/17 07:46

声明器

#include <stdio.h>#include <ctype.h>#include <string.h>#include <stdlib.h>#define MAXLENGTH100#define MAXWORDLENGTH50enum Type_Tag {IDENTIFIER, QUALIFIER, TYPE};struct Words {char name[MAXWORDLENGTH];char type;};int top = -1;struct Words stack[MAXLENGTH];struct Words current;#define push(x)stack[++top] = x#define pop()stack[top--]void Dealwith_Identifier(void);void Dealwith_Declaration(void);void Get_Words(void);enum Type_Tag Classify_Word(void);void Dealwith_Array(void);void Dealwith_Function(void);void Dealwith_Pointer(void);int main(){Dealwith_Identifier();Dealwith_Declaration();return 0;}void Dealwith_Identifier(void){Get_Words();while(current.type != IDENTIFIER) {push(current);Get_Words();}printf("%s is ", current.name);}void Dealwith_Declaration(void){Get_Words();switch(current.type) {case '[':Dealwith_Array();break;case '(':Dealwith_Function();break;}Dealwith_Pointer();while(top != -1) {if(stack[top].type == '(') {pop();Dealwith_Declaration();} elseprintf("%s ", pop().name);}}void Get_Words(void){char *p = current.name;while((*p = getchar()) == ' ');if(isalnum(*p)) {while(isalnum(*++p = getchar()));ungetc(*p, stdin);*p = '\0';current.type = Classify_Word();} else if(*p == '*') {strcpy(p, "pointer to");current.type = '*';} else {current.type = *p;*++p = '\0';}return;}enum Type_Tag Classify_Word(void){char *p = current.name;if(!strcmp(p, "const")) {strcpy(p, "read-only");return QUALIFIER;}if(!strcmp(p, "volatile")) return QUALIFIER;if(!strcmp(p, "char")) return TYPE;if(!strcmp(p, "signed")) return TYPE;if(!strcmp(p, "unsigned")) return TYPE;if(!strcmp(p, "short")) return TYPE;if(!strcmp(p, "int")) return TYPE;if(!strcmp(p, "long")) return TYPE;if(!strcmp(p, "float")) return TYPE;if(!strcmp(p, "double")) return TYPE;if(!strcmp(p, "struct")) return TYPE;if(!strcmp(p, "union")) return TYPE;if(!strcmp(p, "enum")) return TYPE;return IDENTIFIER;}void Dealwith_Array(void){while(current.type == '[') {printf("array ");Get_Words();if(isdigit(current.name[0])) {printf("0...%d ", atoi(current.name)-1);Get_Words();}printf("of ");Get_Words();}}void Dealwith_Function(void){while(current.type != ')')Get_Words();printf("function return ");Get_Words();}void Dealwith_Pointer(void){while(stack[top].type == '*')printf("%s ", pop().name);}


0 0
原创粉丝点击