2
$\begingroup$

I'm trying to do a runtime stack on a simple code example that uses dynamic scoping. The code is this:

void g() {
  int r = 10;
  c = 2;
  b = a;
}

void f() {
  int b;
  b = a;
  a = a + 1;

  g();

  print a, b, c;
}

void main() {
  int a, b, c;
  a = 2;
  b = 4;
  c = 6;

  f();

  print a, b, c; 
}

For the first print, I'm getting 3 3 2, which is correct. However, for the second print (in main) I'm getting 3 3 2 when the correct answer is 3 4 2.

I got 3 3 2 because the value of a is assigned to b which is 3 in function g(), which is called by f(). I don't see b being changed after that.

Appreciate the help!

$\endgroup$
  • $\begingroup$ This programming question is off-topic here. $\endgroup$ – Yuval Filmus Apr 6 '16 at 20:00
  • 4
    $\begingroup$ To me it seems like dynamic scope question with C-ish pseudocode, so it is ontopic. $\endgroup$ – Evil Apr 6 '16 at 20:17
  • 2
    $\begingroup$ Ok. To make it hint (at least for now), do you assume that variable $b$ in main is the same one that in function $f$? $\endgroup$ – Evil Apr 6 '16 at 22:53
  • $\begingroup$ Thanks for the hint! Yes, I did. Once you stated that, I noticed the "int b;" in function f(), that I didn't note before. Thanks for your assistance. $\endgroup$ – user2411290 Apr 7 '16 at 2:52
  • 1
    $\begingroup$ This question only makes sense if you define the scoping rules. Is "dynamic scoping" specific enough? $\endgroup$ – Raphael Apr 7 '16 at 9:01

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.