fork download
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. char input[100]; // Input buffer
  7. int pos = 0; // Current position in input
  8. char token; // Current character (token)
  9. int tempCount = 0; // Temporary variable counter
  10.  
  11. // Function to get next token
  12. void getToken() {
  13. while (input[pos] == ' ' || input[pos] == '\t') pos++;
  14. token = input[pos++];
  15. }
  16.  
  17. // Function to create new temporary variable name
  18. char* newTemp() {
  19. static char temp[10];
  20. sprintf(temp, "t%d", tempCount++);
  21. return strdup(temp);
  22. }
  23.  
  24. // Forward declarations
  25. char* expression();
  26.  
  27. // Function to handle numbers or identifiers
  28. char* factor() {
  29. char* result = (char*)malloc(10);
  30. if (isdigit(token)) {
  31. sprintf(result, "%c", token);
  32. getToken();
  33. } else if (isalpha(token)) {
  34. sprintf(result, "%c", token);
  35. getToken();
  36. } else {
  37. printf("Syntax Error in factor!\n");
  38. exit(1);
  39. }
  40. return result;
  41. }
  42.  
  43. // Function to handle multiplication and division
  44. char* term() {
  45. char* left = factor();
  46. while (token == '*' || token == '/') {
  47. char op = token;
  48. getToken();
  49. char* right = factor();
  50. char* temp = newTemp();
  51. printf("%s = %s %c %s\n", temp, left, op, right);
  52. left = temp;
  53. }
  54. return left;
  55. }
  56.  
  57. // Function to handle addition and subtraction
  58. char* expression() {
  59. char* left = term();
  60. while (token == '+' || token == '-') {
  61. char op = token;
  62. getToken();
  63. char* right = term();
  64. char* temp = newTemp();
  65. printf("%s = %s %c %s\n", temp, left, op, right);
  66. left = temp;
  67. }
  68. return left;
  69. }
  70.  
  71. // Function to handle the assignment statement
  72. void assignment() {
  73. if (!isalpha(token)) {
  74. printf("Syntax Error: Expected identifier on the left-hand side\n");
  75. exit(1);
  76. }
  77.  
  78. char id = token;
  79. getToken();
  80.  
  81. if (token != '=') {
  82. printf("Syntax Error: Expected '=' after identifier\n");
  83. exit(1);
  84. }
  85.  
  86. getToken(); // Skip '='
  87. char* result = expression();
  88.  
  89. if (token != ';') {
  90. printf("Syntax Error: Expected ';' at the end\n");
  91. exit(1);
  92. }
  93.  
  94. printf("%c = %s\n", id, result);
  95. }
  96.  
  97. int main() {
  98. printf("Enter an expression (e.g., a = 3 + 4 * b;): ");
  99. fgets(input, sizeof(input), stdin);
  100.  
  101. getToken();
  102. assignment();
  103.  
  104. return 0;
  105. }
Success #stdin #stdout #stderr 0.03s 6960KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/o4gDxI/prog:105:0: Syntax error: end_of_file_in_quasi_quotation
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit