Home > Software engineering >  C programming file scope and block scope
C programming file scope and block scope

Time:11-26

#include<stdio.h>

int f1(void);
int f2(void);
int f3(void);

int x = 10;

int main()
{
    int x =1;
    x =f1()   f2()   f3()   f2();
    printf("%d", x);
    return 0;
}

int f1()
{
    int x = 25;
    x  ;
    return x;
}
int f2()
{
    static int x= 50; 
    x  ; 
    return x;
}

int f3()
{
    x*=10; 
    return x;
}

Why f3 is taking global x variable? I mean main is calling f3 and In main we have x variable why doesn't f3 take the value of main x variable. Please help

CodePudding user response:

C uses so-called lexical scope. That means that when you use a variable x, you look from the block where you are and outwards until you find the definition of x, and that, then, is the variable you are referring to.

In f3(), you have x, so you look in the block you are inside. There is no definition of x so you look outwards. In this case, outwards is the global scope, because we do not have any nested blocks here.

Lexical scope is not affected by which functions call which other functions. It is a static property of the code, not a dynamic property of the running code. If we used that kind of scope rule, it is called dynamic scope, the x in f3() would depend on who called it at any given time. So the x would be different at different times. There are not many languages that use dynamic scope any longer, because it is damned hard to figure out what variables refer to at any point in the program execution.

It is just different scope rules, and C uses lexical scope and not dynamic scope.

CodePudding user response:

TL;DR Because scope doesn't propagate through function calling.

Here are some blocks that illustrate scope.

scope1

main() {
    scope2
    function();
}

function() {
    scope3
    if () {
        scope4
    }
    scope5
}

scope1 is a "global" scope, that is known and accessible everywhere in your project. If you declare any variables here as "static" they are known only within that file.

scope2 is known in the body of main(). The body of main() also knows and has access to scope1.

scope3 is the same thing as scope5, and the body of function() also knows the global scope1. function() does NOT know scope2, despite being called from there. If you want scope3 or scope5 to know anything about scope2 you must pass that as parameters to function().

scope4 is the body of an if. The body of the if knows scope3 and the global, scope1. Anything declared in scope4 is lost at the end of the block, so scope5 does not know anything about scope4, unless scope4 actually changes the value of a variable declared in scope1 or scope3.

Confusion can easily arise when variables in different levels of nested scope have the same name. This should be avoided!

  •  Tags:  
  • c
  • Related