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 asichanges
๐ Step-by-Step Execution
Initial:
i = 4array = {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 = 5array[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
| Feature | Call by Name | Copy Restore |
|---|---|---|
| Evaluation | Every use | Once (copy) |
| Behavior | Dynamic | Static |
| Complexity | High | Medium |
| Exam Trick | Index changes | Copy 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.