#include <stdio.h> #include <string.h> int tempVar = 1; void newTemp(char *temp) { sprintf(temp, "t%d", tempVar++); } void replace(char expr[][10], int *n, int i, char *temp) { strcpy(expr[i - 1], temp); for (int j = i + 2; j < *n; j++) strcpy(expr[j - 2], expr[j]); *n -= 2; } void generateTAC(char input[]) { char lhs[10], rhs[100]; int n = 0; // Split into lhs and rhs sscanf(input, "%[^=]=%s", lhs, rhs); char expr[50][10], temp[10]; // Tokenize RHS for (int i = 0; rhs[i]; i++) { char t[2] = {rhs[i], '\0'}; strcpy(expr[n++], t); } // First handle * and / for (int i = 0; i < n; i++) if (!strcmp(expr[i], "*") || !strcmp(expr[i], "/")) { newTemp(temp); printf("%s = %s %s %s\n", temp, expr[i - 1], expr[i], expr[i + 1]); replace(expr, &n, i, temp); i = -1; } // Then handle + and - for (int i = 0; i < n; i++) if (!strcmp(expr[i], "+") || !strcmp(expr[i], "-")) { newTemp(temp); printf("%s = %s %s %s\n", temp, expr[i - 1], expr[i], expr[i + 1]); replace(expr, &n, i, temp); i = -1; } // Final assignment printf("%s = %s\n", lhs, expr[0]); } int main() { char expr[100]; printf("Enter expression (e.g., a=b+c*d): "); scanf("%s", expr); generateTAC(expr); return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter