Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables in C++

Tags:

c++

I ran into a interesting issue today. Check out this pseudo-code:

void Loop()
{
   static int x = 1;
   printf("%d", x);
   x++;
}

void main(void)
{
    while(true)
    {
       Loop();
    }
}

Even though x is static, why doesn't this code just print "1" every time? I am reinitializing x to 1 on every iteration before I print it. But for whatever reason, x increments as expected.

like image 702
Blade3 Avatar asked Dec 10 '22 14:12

Blade3


2 Answers

The initialization of a static variable only happens the first time. After that, the instance is shared across all calls to the function.

like image 124
Garo Yeriazarian Avatar answered Dec 12 '22 03:12

Garo Yeriazarian


I am reinitializing x to 1 on every iteration

No, you're not: you're initializing it to 1, but it only gets initialized once.

like image 45
Tim Robinson Avatar answered Dec 12 '22 04:12

Tim Robinson