HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

What are differences between Static Scope and Dynamic Scope?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
whataredifferencesscopebetweendynamicandstatic

Problem

My teacher has provided the following pseudo-code, and says that the output using static scope is 1 2 3, but the output using dynamic scope is 2 3 4.

void fun1(void);
void fun2(void);

int a = 1, b = 2, c = 3;

int main() {
    c = 4;
    fun1();
    return 0;
}

void fun1() {
    int a = 2, b = 3;
    fun2();
}

void fun2(){
    printf("%d %d %d", a, b, c);
}


Which variable we use in Static Scope? $c=3$ or $c=4$? (by Static Scope Rule and without considering C Rules).

Solution

In static scope the $fun2$ takes the globally scoped $c$ which comes from scope where function is defined (opposite to dynamic, where it traverses scopes of execution), so $c = 3$.

With dynamic scope traverses up the chain of scopes until it finds variable it needs, which reflects the fact that scopes are:

Global($a=1, b=2, c=3$) -> main($c=4$) -> fun1 ($a=2, b=3$) -> fun2.

fun2 in the way up finds $a=2, b=3$ in fun1 and $c=4$ in main.

By the way: C has static scope rules.

Context

StackExchange Computer Science Q#52990, answer score: 4

Revisions (0)

No revisions yet.