Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, what happens if two different functions declare the same static variable?

void foo() {
    static int x;
}

void bar() {
    static int x;
}

int main() {
    foo();
    bar();
}
like image 429
Andrew Avatar asked Nov 05 '10 16:11

Andrew


People also ask

Can two static variables have the same name?

Therefore it is possible.

Can static variables be declared twice?

Yes it is. Each of your b variables is private to the function in which they are declared. Show activity on this post. b in func and b in main are two different variables, they are not related, and their scope is inside each function that they are in.

Can two functions declare variables with the same name?

Can two functions declare variables(non static) with the same name? Explanation: We can declare variables with the same name in two functions because their scope lies within the function.

Can static variables be called from another function in C?

Static local variables: variables declared as static inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.


2 Answers

They each see only their own one. A variable cannot be "seen" from outside the scope that it's declared in.

If, on the other hand, you did this:

static int x;

void foo() {
    static int x;
}

int main() {
    foo();
}

then foo() only sees its local x; the global x has been "hidden" by it. But changes to one don't affect the value of the other.

like image 68
Oliver Charlesworth Avatar answered Sep 29 '22 00:09

Oliver Charlesworth


The variables are distinct, each function has it's own scope. So although both variables last for the lifetime of the process, they do not interfere with each other.

like image 25
Ned Batchelder Avatar answered Sep 29 '22 01:09

Ned Batchelder