0

Static variables are stored in data segment of program unlike auto variables which are stored in stack section. Suppose I write code like below.

#include <stdio.h>
void temp();
int main()
{
    static int a=10;
    temp();
    return 0;
}
void temp()
{
    static int a=20;
}

Where same static variable name is defined in 2 functions. In data segment layout there will be 2 variables with same name. Does n't this make confusion at compile/execution time? how this is avoided currently?

3 Answers 3

2

Those two static variables have different scopes so they doesn't conflict, static is storage class which defines where to store the variable. its unrelated with scope of variables.

In data segment layout there will be 2 variables with same name

There isn't any naming in data segment, variables are just identified by their addresses, not names

Sign up to request clarification or add additional context in comments.

Comments

1

Once the compiler has compiled your source file, the variables themselves doesn't exist any more in the generated code, only their locations.

That's why you can have two different static variables with the same name in two different functions.

Not that it really matters how the compiler implement it, as long as it separates variables in different scopes from each other.

Comments

0

In data segment layout there will be 2 variables with same name. Does n't this make confusion at compile/execution time?

This is where the scope of variable comes into play.

a in temp() will shade a in main() when temp() is running. That means when temp() is running the static local variable a is in effect. When control returns to main then the version of a in main is in effect.

3 Comments

No, there is no shadowing here. There would be if there was a global a declared.
@MichaelWalz the shadowing happens regardless of whether it's static or not.
Yes, static doesn't matter, but a (static or not) in temp() doesn't shadow a (static or not) in main(). It would shadow a previously declared global variable a (static or not). Read this for more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.