title: Call by Name with dynamic scoping
body: <p>I am stuck at the following problem on static/dynamic scoping:</p>
  
  <p>The following program fragment is written in a programming language that allows global 
  variables and does not allow nested declarations of functions. </p>
  
  <pre><code> global int i = 100, j = 5; 
   void P(x) { 
    int i = 10; 
    print(x + 10); 
    i = 200; 
    j = 20; 
    print (x); 
   } 
   main() {P(i + j);} 
  </code></pre>
  
  <blockquote>
    <p>Q1.  If the programming language uses static scoping and call by need
    parameter  passing mechanism, the values printed by the above program
    are </p>
    
    <p>(A) 115, 220 (B) 25, 220 (C) 25, 15 (D) 115, 105</p>
    
    <p>Q2.  If the programming language uses dynamic scoping and call by name
    parameter  passing mechanism, the values printed by the above program
    are    </p>
    
    <p>(A) 115, 220 (B) 25, 220 (C) 25, 15 (D) 115, 105</p>
  </blockquote>
  
  <p><strong>What I think:</strong></p>
  
  <p>On Q1: As it's static scoping and as per call by need, x should be replaced with i + j. But it will cause a local name conflict as there is already a variable with name i. So it (the global i) might be renamed, lets say to i1, and then call will be:</p>
  
  <pre><code>   first call: print(x+10) -&gt; (i1 + j + 10) -&gt; (100 + 5 + 10) -&gt; 115
     second call: print(x) -&gt; print(i1 + j) -&gt; 105 (Already evaluated - call by need)
  </code></pre>
  
  <p>On Q2: In dynamic scoping, you search for a variable in the local function first, then you search in the function that called the local function, then you search in the function that called that function, and so on, up the call stack. </p>
  
  <p>As per call by name: </p>
  
  <pre><code>print (i1 + j + 10) -&gt; print (100 + 5 +10 ) -&gt; 115
  </code></pre>
  
  <p>And the second call will be </p>
  
  <pre><code>print(x) -&gt; print(i1 + j) -&gt; (100 + 20) = 120 // Evaluate again - Call be name.
  </code></pre>
  
  <p>Is this answer correct? (Not present in the options)
  Is there something I'm missing? (Dynamic binding may be?)</p>