1
#include<stdio.h>
int x = 12;

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

int main() 
{
  foo(3);
  printf("%d\n",x);
  return 0;
} 

This gives output

3
12

How can i access global int x inside the function foo()?

Aman Sharma
  • 79
  • 2
  • 6
  • 4
    Local variable/parameter shadows the global variable. Just use a different name. `x` is not the most explanatory name for a global, and 99% of the time you don't want to use a global at all. – vgru Oct 30 '20 at 07:55

2 Answers2

0

You can, but the parameter shadows it. Just use another name for parameter variable in foo function.

Itai Klapholtz
  • 196
  • 1
  • 2
  • 15
0

Yes it works like this as variables of same names are allowed provided that they are in different scopes. "x" is both defined in global scope (global variable) and a local scope (in foo() as a parameter). But they are located in different locations in memory.

Rachid K.
  • 4,490
  • 3
  • 11
  • 30