Skip to content

Instantly share code, notes, and snippets.

@prehistoricpenguin
Created December 25, 2012 13:10
Show Gist options
  • Save prehistoricpenguin/4373154 to your computer and use it in GitHub Desktop.
Save prehistoricpenguin/4373154 to your computer and use it in GitHub Desktop.
simple expression parser
/*
* 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