Whe I see this code I would expect something different , I cant understand the meaning of the static variable...I see well the meaning when it's a member data...but here I don't what it does and I believe it's the key...I would expect a rubbish input as it's is increasing value before they are initialized but...it outputs 17...does anyone give an explanation please?
#include <iostream>
#include <stdio.h>
#include <algorithm>
usingnamespace std;
int a;
int b = 2;
int f(void)
{
int x = a++;
{
staticint a;
a = b++;
{
int b = a + x;
x += b;
}
}
return x + a + b;
}
void g(void)
{
printf("%d", f() + f());
}
int main(){
g();
}
the static keyword specifies that the variable retains its state between calls to that function.
But it's irrelevant in your snip, as you are overwriting its state on line 19.
>.I would expect a rubbish input as it's is increasing value before they are initialized
as jlb pointed out, your variables are initialized.
> does anyone give an explanation please?
your code is obfuscated, using meaningless variable names and convoluted statements.
Perhaps you may understand if run step by step with a debugger.
This whole program is all about "hiding" variables and obfuscating logic. The global variables are both being masked/hidden by a variable in the local scope in several places.
what I keep without understanding is....why the global variable is masked as a static, I could understand that once the execution of the program gets that point( where a is defined as a static), but in the meantime it should contain rubbish and that rubbish affects directly to the final result......
And yes, jlb that code was made specifically to challenge the knowledge about scopes (local and global variables) I though I knew in theory at least roughly but I guess I dont....heehehehe
what I keep without understanding is....why the global variable is masked as a static, I could understand that once the execution of the program gets that point( where a is defined as a static), but in the meantime it should contain rubbish and that rubbish affects directly to the final result......
But remember, static and global variables are both initialized to zero, unless assigned another value.
The purpose of that static qualification is two fold in this program. The first time through that section of the code a is initialized to zero. The next time through the loop a will contain the value of b (before the increment). Remember a static variable will retain it's value between "calls". And don't forget about all of those "extra" scopes throughout the program.