fork download
  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4.  
  5. // Original function with nested blocks
  6. void F(int n) {
  7. int x = n * 2;
  8. int y = n + 3;
  9. int z = 0;
  10.  
  11. // Block 1
  12. if (n > 0) {
  13. int a = x + 1;
  14. int b = y - 1;
  15.  
  16. // Block 2
  17. {
  18. int d = a * 2;
  19. int e = b / 2;
  20. z += d + e;
  21. }
  22. }
  23.  
  24. // Block 3
  25. if (n > 1) {
  26. int f = y + 10;
  27. int g = x - 5;
  28. z += f - g;
  29. }
  30.  
  31. cout << "F(" << n << "): " << z << endl;
  32. }
  33.  
  34. // Iterative implementation with single fb variable
  35. struct ActivationRecord {
  36. int n;
  37. int x, y, z; // Persistent variables
  38.  
  39. // Temporary variables (only one set used at a time)
  40. int temp1, temp2;
  41.  
  42. int fb; // Current flattened block (0-3)
  43.  
  44. ActivationRecord(int n) : n(n), x(0), y(0), z(0), fb(0) {}
  45. };
  46.  
  47. void G(int n) {
  48. stack<ActivationRecord> st;
  49. st.push(ActivationRecord(n));
  50.  
  51. while (!st.empty()) {
  52. ActivationRecord& ar = st.top();
  53.  
  54. switch (ar.fb) {
  55. case 0: // Initialization
  56. ar.x = ar.n * 2;
  57. ar.y = ar.n + 3;
  58. ar.z = 0;
  59. ar.fb = 1;
  60. break;
  61.  
  62. case 1: // Block 1
  63. if (ar.n > 0) {
  64. ar.temp1 = ar.x + 1; // a
  65. ar.temp2 = ar.y - 1; // b
  66. ar.fb = 2;
  67. } else {
  68. ar.fb = 3;
  69. }
  70. break;
  71.  
  72. case 2: // Block 2
  73. {
  74. int d = ar.temp1 * 2; // using temp1 as a
  75. int e = ar.temp2 / 2; // using temp2 as b
  76. ar.z += d + e;
  77. ar.fb = 3;
  78. break;
  79. }
  80.  
  81. case 3: // Block 3
  82. if (ar.n > 1) {
  83. ar.temp1 = ar.y + 10; // f
  84. ar.temp2 = ar.x - 5; // g
  85. ar.z += ar.temp1 - ar.temp2;
  86. }
  87. cout << "G(" << ar.n << "): " << ar.z << endl;
  88. st.pop();
  89. break;
  90. }
  91. }
  92. }
  93.  
  94. int main() {
  95. cout << "Original function F():\n";
  96. for (int i = 0; i < 5; i++) F(i);
  97.  
  98. cout << "\nIterative version G():\n";
  99. for (int i = 0; i < 5; i++) G(i);
  100.  
  101. return 0;
  102. }
Success #stdin #stdout 0.01s 5308KB
stdin
Standard input is empty
stdout
Original function F():
F(0): 0
F(1): 7
F(2): 28
F(3): 31
F(4): 35

Iterative version G():
G(0): 0
G(1): 7
G(2): 28
G(3): 31
G(4): 35