Andrew
Andrew

Reputation: 1650

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();
}

Upvotes: 8

Views: 2901

Answers (6)

Zac
Zac

Reputation: 4705

The compilator translates each variable in a unique manner, such as foo_x and bar_x in your example, so they are threated differently.

Don't do this as your code will be hard to read and maintain after some time since you will not able to catch at once of what x are you referring to.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272667

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.

Upvotes: 20

pyCoder
pyCoder

Reputation: 501

Nothing happen, both variables have theri scope and mantain their values to call in call

Upvotes: 2

peoro
peoro

Reputation: 26060

The two static vars are different.

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375784

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.

Upvotes: 6

This is perfectly fine. In practice the actual name of the variable in the output of the compiler can be thought of as something like function_bar_x, i.e. it is the responsibility of your compiler to ensure that these do not clash.

Upvotes: 3

Related Questions