Search code examples
c++cscopeprogramming-languages

Do mainstream programming languages today mostly use dynamic or static(lexical) scope?


I have read this question, and I think I've understood the most upvoted answer, but he said

since basically every programming language in wide use today uses lexical scoping

I also heard this from coursera programming language, but here's a simple C code:

#include <stdio.h>

int x = 1;

void fun(){
    printf("%d\n", x);
}

void dummy1(){
    x = 2;
    fun();
}

void dummy2(){
    x = 3;
    fun();
}


int main(){

    x = 4;

    fun();
    dummy1();
    dummy2();

    return 0;
}

output:

4
2
3

C++ have exactly the same behavior, so I think C and C++ are dynamic scoped language, are they? And is it real that most programming languages use static scope?


Solution

  • What you have is not dynamic scoping. You aren't introducing any new variables but using the same global one. If C and C++ had dynamic scoping then this (note that each x is a new variable):

    #include <stdio.h>
    
    int x = 1;
    
    void fun(){
        printf("%d\n", x);
    }
    
    void dummy1(){
        int x = 2;
        fun();
    }
    
    void dummy2(){
        int x = 3;
        fun();
    }
    
    
    int main(){
    
        int x = 4;
    
        fun();
        dummy1();
        dummy2();
    
        return 0;
    }
    

    would output

    4
    2
    3
    

    but instead it outputs

    1
    1
    1
    

    Since fun() is always using the same global x initialized to 1. This is because C and C++ use static lexical scoping.