Skip to content

Instantly share code, notes, and snippets.

@kdridi
Created October 18, 2020 22:50
Show Gist options
  • Save kdridi/d7a8a4e8109aab2b70ce5aaddb4c5452 to your computer and use it in GitHub Desktop.
Save kdridi/d7a8a4e8109aab2b70ce5aaddb4c5452 to your computer and use it in GitHub Desktop.
#include <stdio.h>
void read_term(const char **ptr);
void read_factor(const char **ptr);
void read_number(const char **ptr);
void read_term(const char **ptr)
{
read_factor(ptr);
if (**ptr == '+') {
*ptr += 1;
read_term(ptr);
printf("operator: +\n");
}
if (**ptr == '-') {
*ptr += 1;
read_term(ptr);
printf("operator: -\n");
}
}
void read_factor(const char **ptr)
{
read_number(ptr);
if (**ptr == '*') {
*ptr += 1;
read_factor(ptr);
printf("operator: *\n");
}
if (**ptr == '/') {
*ptr += 1;
read_factor(ptr);
printf("operator: /\n");
}
if (**ptr == '%') {
*ptr += 1;
read_factor(ptr);
printf("operator: %%\n");
}
}
void read_number(const char **ptr)
{
if (**ptr == '+') {
*ptr += 1;
read_number(ptr);
} else if (**ptr == '-') {
*ptr += 1;
read_number(ptr);
printf("operator: negate\n");
} else if (**ptr == '(') {
*ptr += 1;
read_term(ptr);
*ptr += 1;
} else {
char number[256];
{
const char *str = *ptr;
{
size_t i = 0;
while ('0' <= *str && *str <= '9') {
number[i++] = *(str++);
}
number[i] = 0;
}
*ptr = str;
}
printf("number: %s\n", number);
}
}
int main(void)
{
const char *expr = "10*(12+(3*10+4))";
read_term(&expr);
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment