Search code examples
cfunctionscope

Why function uses the global variable and skip the local one when we have 2 variables with the same identifier


As far as I know that when I use a function it creates a stack frame nested from the main stack frame and depending on that it's supposed that when a variable being referenced to and it isn't declared in the function scope the function gradually goes to the larger scope so here it should go to the Local scope before it jump to the Global, or I'm misunderstanding it ?

#include <stdio.h>
#include <windows.h>

int X = 2;
void Scope(void);

int main()
{
    int X = 3;
    Scope();

    return 0;
}
void Scope(void)
{
    printf("Entering X = %d\n" ,X);
    printf("Exiting  X = %d\n" , X*X);
}

Solution

  • In your example X from main is not visible from function Scope as Scope is a separate function and it does not see automatic storage duration variables from other functions. It can only see the "global" or compilation unit static storage duration variables.