home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
ftp.disi.unige.it
/
2015-02-11.ftp.disi.unige.it.tar
/
ftp.disi.unige.it
/
pub
/
.person
/
CataniaB
/
teach-act
/
laboratorio
/
lab-26-4-99
/
interprete.c
< prev
next >
Wrap
C/C++ Source or Header
|
1999-05-25
|
2KB
|
147 lines
#include <stdio.h>
#include <stdlib.h>
#define NOFSYM 8
typedef enum {NOTREC = -2,
PLUS =0, MINUS, TIMES, DIV, MOD, EQUAL, LPAR, RPAR, NUMBER} symkind;
typedef struct {symkind kind;int value;} symbol;
const char tab[NOFSYM] = {'+','-','*','/','%','=','(',')'};
symbol getsym();
static symbol sym;
int inte(void);
int inteE(void);
int inteT(void);
int inteF(void);
main()
{int val;
printf("\n\nIl valore dell'espressione e': %d \n\n",inte());
return 0;
}
int inte(void)
{
int val;
sym =getsym();
val =inteE();
if (sym.kind==EQUAL)
return val;
else
{
printf("errore in inte");
exit(EXIT_FAILURE);
}
}
int inteE(void)
{
int val;
val = inteT();
if (sym.kind==PLUS)
{
sym=getsym();
val = val +inteE();
}
else if (sym.kind ==MINUS)
{
sym=getsym();
val = val -inteE();
}
return val;
}
int inteT(void)
{
int val;
val=inteF();
if (sym.kind == TIMES)
{
sym=getsym();
val = val * inteT();
}
else if (sym.kind == DIV)
{ sym=getsym();
val = val / inteT();
}
return val;
}
int inteF(void)
{
int val;
switch (sym.kind)
{
case LPAR:
sym=getsym();
val = inteE();
if (sym.kind !=RPAR)
{
printf("errore in inteF");
exit(EXIT_FAILURE);
}
sym=getsym();
break;
case MINUS:
sym=getsym();
val = -1 * inteF();
break;
case NUMBER:
val=sym.value;
sym = getsym();
break;
default :
printf("errore in inteF");
exit(EXIT_FAILURE);
break;
}
return val;
}
symbol getsym()
{
symbol s;
static char c = ' ';
s.kind = NOTREC;
while (c != EOF && (c == ' ' || c == '\n' || c == '\t'))
c = getchar();
if (c == EOF)
{
s.kind =EOF;
return s;
}
if (c >= '0' && c <= '9')
{
s.kind =NUMBER;
s.value =0;
do
s.value = s.value * 10 + c - '0';
while ((c = getchar()) != EOF && c >= '0' && c <= '9');
}
else
{
symkind i;
for (i = PLUS; i <= RPAR; i++)
if (tab[i] == c)
s.kind = i;
c= getchar();
}
return s;
}