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.
The initialization of a static variable only happens the first time. After that, the instance is shared across all calls to the function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With