Write a C program to generate three address code.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 100
int tempCount = 1;
// Generate temporary variable name
char* newTemp() {
static char temp[10];
sprintf(temp, "t%d", tempCount++);
return temp;
}
// Check operator precedence
int precedence(char op) {
if (op == '*' || op == '/') return 2;
if (op == '+' || op == '-') return 1;
return 0;
}
// Convert infix to postfix
void infixToPostfix(char* infix, char postfix[][20], int* postIndex) {
char stack[MAX];
int top = -1;
int i = 0;
while (infix[i] != '\0') {
if (isspace(infix[i])) {
i++;
continue;
}
if (isalnum(infix[i])) {
int j = 0;
char token[20] = "";
while (isalnum(infix[i])) {
token[j++] = infix[i++];
}
token[j] = '\0';
strcpy(postfix[(*postIndex)++], token);
} else if (infix[i] == '(') {
stack[++top] = infix[i++];
} else if (infix[i] == ')') {
while (top >= 0 && stack[top] != '(') {
char op[2] = {stack[top--], '\0'};
strcpy(postfix[(*postIndex)++], op);
}
if (top >= 0 && stack[top] == '(') top--; // Remove '('
i++;
} else { // Operator
while (top >= 0 && precedence(stack[top]) >= precedence(infix[i])) {
char op[2] = {stack[top--], '\0'};
strcpy(postfix[(*postIndex)++], op);
}
stack[++top] = infix[i++];
}
}
while (top >= 0) {
char op[2] = {stack[top--], '\0'};
strcpy(postfix[(*postIndex)++], op);
}
}
// Generate TAC from postfix
void generateTACFromPostfix(char postfix[][20], int postIndex, char* lhs) {
char stack[MAX][20];
int top = -1;
for (int i = 0; i < postIndex; i++) {
if (isalnum(postfix[i][0]) && postfix[i][1] == '\0') {
// Single-letter operand
strcpy(stack[++top], postfix[i]);
} else if (isalnum(postfix[i][0])) {
// Multi-letter variable (e.g., num1)
strcpy(stack[++top], postfix[i]);
} else {
char op2[20], op1[20];
strcpy(op2, stack[top--]);
strcpy(op1, stack[top--]);
char* temp = newTemp();
printf("%s = %s %s %s\n", temp, op1, postfix[i], op2);
strcpy(stack[++top], temp);
}
}
printf("%s = %s\n", lhs, stack[top]);
}
void generateTAC(char expr[]) {
// Remove spaces
char cleanExpr[100] = "";
int i, j = 0;
for (i = 0; expr[i] != '\0'; i++) {
if (!isspace(expr[i]))
cleanExpr[j++] = expr[i];
}
cleanExpr[j] = '\0';
// Split into LHS and RHS
char lhs[20], rhs[100];
char* eqPos = strchr(cleanExpr, '=');
if (eqPos == NULL) {
printf("Invalid expression (missing '=').\n");
return;
}
strncpy(lhs, cleanExpr, eqPos - cleanExpr);
lhs[eqPos - cleanExpr] = '\0';
strcpy(rhs, eqPos + 1);
// Convert RHS to postfix
char postfix[MAX][20];
int postIndex = 0;
infixToPostfix(rhs, postfix, &postIndex);
// Generate TAC from postfix
generateTACFromPostfix(postfix, postIndex, lhs);
}
int main() {
char expr[100];
printf("Enter an arithmetic expression (e.g., a = b + c * d / e):\n");
fgets(expr, sizeof(expr), stdin);
expr[strcspn(expr, "\n")] = 0; // Remove newline
generateTAC(expr);
return 0;
}