319 views
0 votes
0 votes

Are any modifications to the value of a dynamically scoped variable persistent even after the function (in which modifications were made) returns? For example, in the following code (assuming dynamic scoping):

void weird_function (int i)
{
    i = 5;
    return;
}

int main (void)
{
    int i = 4;
    weird_function(i);
    printf(“%d\n”, i);
    return 0;
}

ignoring call-by-value semantics; when the control returns to main after calling weird_function, would the variable i (which is dynamically scoped) contain 4 or 5?

 

In other words, would the dynamically scoped variables be allocated on heap or do they live in the stack frame of current function? Do dynamically scoped variables essentially act like global variables in this particular regard?

1 Answer

Best answer
1 votes
1 votes

I actually found the answer — the new value (5) will persist. Following is a possible implementation of dynamic scoping which makes it clear:

  • Each time a subroutine is called, its local variables are pushed on a stack with their name-to-object binding
  • When a reference to a variable is made, the stack is searched top-down for the variable's name-to-object binding
  • After the subroutine returns, the bindings of the local variables are popped.

EDIT: Turns out, Bash is a dynamically scoped language. Try the following in a Bash shell:

$ i=1
$ function f () { local i=3 ; g ; echo "f: $i" ; }
$ function g () { echo "g: $i" ; i=2 ; }
$ f

Output will be:

g: 3
f: 2
edited by

Related questions

2 votes
2 votes
4 answers
1
admin asked Mar 31, 2020
1,032 views
How will you free the allocated memory?remove(var-name)free(var-name)delete(var-name)dalloc(var-name)
0 votes
0 votes
2 answers
3