How to access a global variable that has the same name as the local variable in C?

When we have a local variable with the same name as the global variable, we can’t access the value of the global variable as the environment always points to the value of the local variable.

For Example:

#include<stdio.h>

int x = 10; // global variable 

int main()
{
  int x = 50; // local variable
  
  printf("Value of X is %d\n",x);

  return 0;
}
OUTPUT:
Value of X is 50

In such a case, we may use ‘extern’ to access the value of a global variable.

For Example:

#include<stdio.h>

int x = 10; // global variable 

int main()
{
  int x = 50; // local variable
  
  {
    extern int x;
    printf("Value of X (Global Variable) is %d\n",x);
  }
  printf("Value of X (Local Variable) is %d\n",x);

  return 0;
}
OUTPUT:
Value of X (Global Variable) is 10
Value of X (Local Variable) is 50

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.