geekhack
geekhack Community => Off Topic => Topic started by: Lastpilot on Wed, 01 May 2013, 19:51:17
-
Given the function definition
void Test (/* in */ int alpha)
{
static int n = 5;
n = n + alpha;
cout << n << ' ';
}
what is the output of the following code? (assume Test has not been called previously)
Test (20);
Test (30);
The answer is 25 55.....why isnt it just 25 35?
-
static. It remembers.
-
static. It remembers.
What he said.
-
So does that mean that the "= 5" part doesn't matter on the second function call?
-
Yes, once it is initialized it doesn't get initialized again.
-
Ah okay I get it. Thanks guys!
-
Note that reinitializing n each time would defeat the purpose of declaring it to be static. It would have no way to retain its value between calls.
-
static int n = 5 /* or just use int n = 5 */
void Test (/* in */ int alpha)
{
alpha = n + alpha;
cout << alpha << ' ';
}
that should return what you're looking for
test(20) -> 25
test(30) -> 35
-
That is not correct code.