Created
December 25, 2012 13:10
-
-
Save prehistoricpenguin/4373154 to your computer and use it in GitHub Desktop.
simple expression parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* simple expression parser | |
* example: 1+2-3 -> 12+3- | |
*/ | |
#include <stdio.h> | |
#include <ctype.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
int lookahead; | |
void parser () | |
{ | |
lookahead = getchar(); | |
} | |
void expr () | |
{ | |
term(); | |
while (true) | |
{ | |
if (lookahead == '+') | |
{ | |
match('+'); | |
term(); | |
putchar('+'); | |
} | |
else if (lookahead == '-') | |
{ | |
match('-'); | |
term(); | |
putchar('-'); | |
} | |
else | |
return; | |
} | |
} | |
void term() | |
{ | |
if (isdigit((char)lookahead)) | |
{ | |
putchar((char)lookahead); | |
match(lookahead); | |
} | |
else | |
{ | |
fprintf(stderr,"syntax error"); | |
exit(EXIT_FAILURE); | |
} | |
} | |
void match(int t) | |
{ | |
if (lookahead == t) | |
lookahead = getchar(); | |
else | |
{ | |
fprintf(stderr,"syntax error"); | |
exit(EXIT_FAILURE); | |
} | |
} | |
int main() | |
{ | |
parser(); | |
expr(); | |
putchar('\n'); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment