Last active
November 7, 2018 10:31
-
-
Save AmalJossy/2a66b1ea2274f62d4fabeaff30aa0458 to your computer and use it in GitHub Desktop.
Intermediate code generator
This file contains hidden or 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
#include <stdio.h> | |
#include<string.h> | |
#include<ctype.h> | |
#define MAX_SIZE 100 | |
char expr[MAX_SIZE] = {0}; | |
char STACK[MAX_SIZE] = {0}, POST[MAX_SIZE] = {0}; | |
int top=-1; | |
int rear=-1,front=-1; | |
char TEMPS='0'; | |
void push(char x){ | |
top++; | |
STACK[top]=x; | |
} | |
char pop(){ | |
char ch=STACK[top]; | |
top--; | |
return ch; | |
} | |
int precedence(char op){ | |
switch(op){ | |
case '*':case '/': return 5; | |
case '+':case '-':return 3; | |
case '=': return 2; | |
default: return 1; | |
} | |
} | |
void enqueue(char ch){ | |
rear++; | |
POST[rear]=ch; | |
} | |
void createPostFix(char *expr){ | |
int i,len=strlen(expr); | |
char op; | |
for(i=0;i<len;i++){ | |
if(isalpha(expr[i])){ | |
enqueue(expr[i]); | |
} | |
else{ | |
switch(expr[i]){ | |
case '(':push(expr[i]);break; | |
case ')':while(STACK[top]!='('){ | |
enqueue(pop()); | |
}break; | |
default: | |
while(precedence(expr[i]) <= precedence(STACK[top])){ | |
enqueue(pop()); | |
} | |
push(expr[i]); | |
} | |
} | |
} | |
while(top!=-1){ | |
op=pop(); | |
if(op!='(') | |
enqueue(op); | |
} | |
} | |
char getTemp(){ | |
return TEMPS++; | |
} | |
void printCode(int i){ | |
char operand1,operand2,operator; | |
operand2=pop(); | |
operand1=pop(); | |
operator=POST[i]; | |
if(operator=='='){ | |
printf("%c = %c \n",operand1,operand2); | |
return; | |
} | |
char newTemp=getTemp(); | |
push(newTemp); | |
printf("%c = %c %c %c\n",newTemp,operand1,operator,operand2 ); | |
} | |
int main(){ | |
int len,i; | |
scanf("%s", expr); | |
createPostFix(expr); | |
len=strlen(POST); | |
for(i=0;i<top;i++){ | |
STACK[i]=0; | |
} | |
for(i=0;i<len;i++){ | |
if(isalpha(POST[i])){ | |
push(POST[i]); | |
} | |
else{ | |
printCode(i); | |
} | |
} | |
// printf("\n%s : %lu\n", POST, strlen(POST)); | |
// printf("%s\n", STACK); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment