Eukleides project

from http://d.hatena.ne.jp/u5_h/

(構造関係・コンパイラ)字句解析lexical analysis

逆ポーランド記法(後順操作)を演算するプログラム
これもいつかの課題ですが同じ手法が字句解析の応用されています。
lexと呼ばれています。これに構文解析yaccがあって基本的なコンパイラを作成し、自分の定義した文法規則に従うプログラミング言語を開発可能です。
#include
#include
#include

struct cell
{
double data;
struct cell *next;
};

struct cell *listhead=NULL;

void push(double);
void pop(double *);

int main(void)
{
int c;
double op, op1, op2, val;
whilenext)
{
pop(&op);
printf("答えは %f です.\n",op);
}
else
{
printf("ERROR\n");
}
return 0;
}
void push(double x)
{
struct cell *p;
p=listhead;
listhead=(struct cell *)malloc(sizeof(struct cell">*1
;
listhead->data=x;
listhead->next=p;
}

void pop(double *p)
{
struct cell *q;
if(listhead)
{
*p=listhead->data;
q=listhead;
listhead=listhead->next;
free((void *)q);
}
else
{
printf("スタックにデータがありません。\n");
exit(1);
}
}

*1: c = getchar() ) != '\n') { if( isdigit(c) ) { ungetc(c,stdin); scanf("%lf",&val); push(val); } else { switch(c) { case '+': pop(&op2); pop(&op1); push(op1+op2); break; case '-': pop(&op2); pop(&op1); push(op1-op2); break; case '*': pop(&op2); pop(&op1); push(op1*op2); break; case '/': pop(&op2); pop(&op1); if(op2 == 0) { printf("0 による除算はできません。\n"); exit(1); } push(op1/op2); break; } } } if(!listhead->next) { pop(&op); printf("答えは %f です.\n",op); } else { printf("ERROR\n"); } return 0; } void push(double x) { struct cell *p; p=listhead; listhead=(struct cell *)malloc(sizeof(struct cell