fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. // Structure to represent a three-address code instruction
  6. typedef struct Instruction {
  7. char operator[5];
  8. char operand1[10];
  9. char operand2[10];
  10. char result[10];
  11. } Instruction;
  12.  
  13. // Function to generate three-address code for an expression
  14. void generateTAC(char *expression, Instruction *instructions, int *count) {
  15. char *token;
  16. char *rest = expression;
  17. char operators[10];
  18. char operands[10][10];
  19. int top_op = -1;
  20. int top_val = -1;
  21. int temp_count = 1;
  22.  
  23. // Tokenize the expression
  24. while ((token = strtok_r(rest, " ", &rest)) != NULL) {
  25. if (token[0] == '+' || token[0] == '-' || token[0] == '*' || token[0] == '/') {
  26. operators[++top_op] = token[0];
  27. } else if (token[0] >= 'a' && token[0] <= 'z') {
  28. strcpy(operands[++top_val], token);
  29. }
  30. }
  31.  
  32. // Generate three-address code
  33. while (top_op >= 0) {
  34. Instruction instruction;
  35. char temp[10];
  36.  
  37. // Pop operator and operands
  38. char op = operators[top_op--];
  39. char *operand2 = operands[top_val--];
  40. char *operand1 = operands[top_val--];
  41.  
  42. // Create temporary variable
  43. sprintf(temp, "t%d", temp_count++);
  44.  
  45. // Fill instruction fields
  46. sprintf(instruction.operator, "%c", op);
  47. strcpy(instruction.operand1, operand1);
  48. strcpy(instruction.operand2, operand2);
  49. strcpy(instruction.result, temp);
  50.  
  51. // Add instruction to the list
  52. instructions[(*count)++] = instruction;
  53.  
  54. // Push result back to operands stack
  55. strcpy(operands[++top_val], temp);
  56. }
  57. }
  58.  
  59. int main() {
  60. char expression[100];
  61. Instruction instructions[100];
  62. int instruction_count = 0;
  63.  
  64. // Get expression from user
  65. printf("Enter an arithmetic expression (e.g., a + b * c): ");
  66. fgets(expression, sizeof(expression), stdin);
  67. expression[strcspn(expression, "\n")] = 0; // Remove trailing newline
  68.  
  69. // Generate three-address code
  70. generateTAC(expression, instructions, &instruction_count);
  71.  
  72. // Print three-address code
  73. printf("\nThree-Address Code:\n");
  74. for (int i = 0; i < instruction_count; i++) {
  75. printf("%s = %s %s %s\n", instructions[i].result, instructions[i].operand1,
  76. instructions[i].operator, instructions[i].operand2);
  77. }
  78.  
  79. return 0;
  80. }
Success #stdin #stdout 0s 5324KB
stdin
Standard input is empty
stdout
Enter an arithmetic expression (e.g., a + b * c): 
Three-Address Code: