๐Ÿง  Call by Name vs Copy Restore (With Solved Program)

Parameter passing techniques are a favorite topic in compiler design exams. Questions often test your understanding using tricky programs.

In this post, weโ€™ll:

  • Understand call by name and copy restore
  • Solve a real exam-level question step by step

๐Ÿ”ต Given Program

void func(int a, int b)
{
a = a + b;
b = a + b;
a = b - a;
b = a - b;
}main()
{
int j, i = 4;
int array[10] = {1,2,3,4,5,6,7,8,9,0}; func(i, array[i]); for(j = 0; j < 10; j++)
printf("%d", array[j]);
}

๐Ÿ”ด Concept 1: Call by Name

๐Ÿง  Key Idea:

  • Arguments are re-evaluated every time they are used
  • array[i] changes dynamically as i changes

๐Ÿ” Step-by-Step Execution

Initial:

  • i = 4
  • array = {1,2,3,4,5,6,7,8,9,0}

Step 1:

a = a + b โ†’ i = i + array[i] = 4 + 5 = 9

Step 2:

b = a + b โ†’ array[i] = i + array[i]
โ†’ array[9] = 9 + 0 = 9

Step 3:

a = b - a โ†’ i = array[i] - i
โ†’ i = 9 - 9 = 0

Step 4:

b = a - b โ†’ array[i] = i - array[i]
โ†’ array[0] = 0 - 1 = -1

โœ… Final Array (Call by Name)

-1 2 3 4 5 6 7 8 9 9

๐Ÿ”ด Concept 2: Copy Restore (Call by Value-Result)

๐Ÿง  Key Idea:

  • First: values are copied into parameters
  • Then: operations happen on local variables
  • Finally: values are copied back

๐Ÿ” Step-by-Step Execution

Initial:

  • a = 4, b = 5 (since array[4] = 5)

Step 1:

a = a + b = 4 + 5 = 9

Step 2:

b = a + b = 9 + 5 = 14

Step 3:

a = b - a = 14 - 9 = 5

Step 4:

b = a - b = 5 - 14 = -9

๐Ÿ” Copy Back:

  • i = a = 5
  • array[4] = b = -9

โœ… Final Array (Copy Restore)

1 2 3 4 -9 6 7 8 9 0

๐ŸŽฏ Final Answer

๐Ÿ‘‰ Call by Name:
-1 2 3 4 5 6 7 8 9 9

๐Ÿ‘‰ Copy Restore:
1 2 3 4 -9 6 7 8 9 0


โšก Exam Tricks

  • Call by Name โ†’ dynamic evaluation (very tricky)
  • Copy Restore โ†’ copy โ†’ operate โ†’ copy back
  • Watch for changing indices like array[i]

๐Ÿง  Quick Comparison

FeatureCall by NameCopy Restore
EvaluationEvery useOnce (copy)
BehaviorDynamicStatic
ComplexityHighMedium
Exam TrickIndex changesCopy back matters

๐ŸŽฏ Conclusion

Understanding parameter passing techniques is crucial for solving tricky compiler design questions. Always track variable changes carefully, especially in call by name.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *