2
$\begingroup$

I'm wondering about the result of this program as I get confused when it comes to lexical scoping and dynamic scoping.

fun bar() {
   int a = 2
   void foo(int b) {
       b = b * a;
       a = a - b     
   }
   {
       int a = 10;
       foo(a);
       print a;
   }
}

There are a couple of questions of what program will print, and here are my answers

  • Call-by-value and lexical scoping: 10 because call-by-value does not change the value of variable a after calling foo(a), and within the scope of $ print $ a is 10.
  • Call-by-value and dynamic scoping: 10 just as the above, call-by-value does not change the value of a
  • Call-by-reference and lexical scoping:
  • Call-by-reference and dynamic scoping:

I get confused about the last two options. I'm wondering whether with lexical scoping it will use the value a = 10, or a = 2 in foo function, i.e. I'm not sure what will be printed 20 or 100. The confusion also holds with call-by-reference dynamic scoping

$\endgroup$
  • 1
    $\begingroup$ Good question but I don't think CS is the right place to ask. The first question will get closed as we don't check homework here. The second question will get closed as we don't talk about specific language code here. If you are uncertain about one or more of your solutions then I would suggest you repose the question showing what you did step by step to get the answer, and then for the part you unsure of, ask a question about that. $\endgroup$ – Guy Coder Dec 9 '13 at 1:06
  • 1
    $\begingroup$ This question appears to be off-topic because questions of the form: "This is the exercises problem, this is my solution. Please grade!" are not a good fit for this site. Please see this related meta discussion. If you want to ask a specific question about a specific part of your attempt, please edit the question accordingly and it may be reopened. $\endgroup$ – D.W. Dec 9 '13 at 2:51
  • $\begingroup$ This question is impossible to answer without reference to the programming language you're using; which strongly suggests that Stack Overflow would be a better forum. $\endgroup$ – reinierpost Dec 9 '13 at 10:26
  • $\begingroup$ Rename the variables, and rewrite your program to access the lexically/dynamically scoped one(s). This helps in wrapping the brain around what is going on. $\endgroup$ – vonbrand Jan 29 '14 at 22:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.