RoG
RoG

Reputation: 421

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.

Upvotes: 3

Views: 1734

Answers (4)

molbdnilo
molbdnilo

Reputation: 66459

Those are usually called dynamic and lexical scoping.

Lexical scoping is determined entirely at compile time, dynamic scoping at runtime.

You only have one variable named "x", so scope is irrelevant to your program.

Here's a program that would be different depending on the scoping rules:

int x = 0;

int f()
{
    return x;
}

int main()
{
    int x = 1;
    printf("%d\n", f(x));
}

Under lexical scoping, f returns the value of the x that is lexically "nearest" - the global one.
So it would print 0;

Under dynamic scoping, f would return the value of the newest x, which is the one in main.
So it would print 1.

Upvotes: 3

JHBonarius
JHBonarius

Reputation: 11291

It is the way the compiler generates the assembly/machine code.

  • first global variable X is stored in memory location "abc"
  • next main is executed: global variable X at "abc" is changed to 2
  • Now function f() is called:
    • function f returns the value of global variable X at "abc": being 2
  • the return value of f() is printed.

So if you wanted a different X in the main-function scope, you should have made a new object, like in the answer by nwp.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234875

The scoping is moot here since you have not declared an x locally that would have otherwise shadowed the global x.

2 is printed.

x is assigned in main to 2 immediately before f is called with the parameter 0.

(Conceptually int x = 1; is ran before main is entered.)

Upvotes: 2

nwp
nwp

Reputation: 10011

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.

Upvotes: 9

Related Questions