Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static scoping in C/C++

In the following code, 2 is printed.

int x = 1;
int f(int y)
{
    return x;
}

int main() {
    x = 2;
    printf("%d", f(0));
}

How is it happening if we have static scoping in C? Why isn't 1 printed?

Printing 2 in this case isn't a dynamic scoping, is it?

I thought that in static scoping it should take the nearest x to the function definition.

like image 467
RoG Avatar asked Apr 27 '26 12:04

RoG


1 Answers

It does take the nearest x, but since you only have one x it doesn't really matter.

If you change the code to

int x = 1;
int f(int y)
  {
    return x ;
  }

int main() {
    int x=2;       
    printf("%d", f(0));
}

so you have 2 x, the global one and the local one in main you will see 1 getting printed.

like image 66
nwp Avatar answered Apr 30 '26 02:04

nwp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!