Friday, January 6, 2012

static scoping(lexical) vs dynamic scoping

Statically typed languages check types at compile time
The programmer ensures that parameter types are specified and the compiler ensures the programmers wishes will be followed.

In a dynamically typed language (like ruby, javascript, etc), types are not checked until execution
If an expression evaluates, then the type-checking worked. If not, it blows up to your error handling or the user

Static Scoping – Variables can be bound at compile time without regards to calling code.

Dynamic Scoping – Variable binding (context) can only be determined at the moment code is executed.



Reference:
http://hoolihan.net/blog-tim/2009/02/17/static-vs-dynamic-scope/
http://en.wikipedia.org/wiki/Scope_%28programming%29




  • First, Lexical Scope (also called Static Scope), in C-like syntax:

void fun()
{
    int x = 5;

    void fun2()
    {
        printf("%d", x);
    }
}
Every inner level can access its outer levels.
There is another way, called Dynamic Scope used by first implementation of Lisp, again in C-like Syntax:
void fun()
{
    printf("%d", x);
}

void dummy1()
{
    int x = 5;

    fun();
}

void dummy2()
{
    int x = 10;

    fun();
}
Here fun can either access x in dummy1 or dummy2, or any x in any function that call fun with xdeclared in it.
dummy1();
will print 5
dummy2();
will print 10

The first one is called static because it can be deduced at compile-time, the second is called dynamic because the outer scope is dynamic and depends on the chain call of the functions.
Dynamic scoping is like passing references of all variables to the called function.
stackoverflow

No comments:

Post a Comment