geekhack

geekhack Community => Off Topic => Topic started by: Lastpilot on Wed, 01 May 2013, 19:51:17

Title: C++ Study Help? [solved]
Post 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?
Title: Re: C++ Study Help?
Post by: hashbaz on Wed, 01 May 2013, 20:01:37
static.  It remembers.
Title: Re: C++ Study Help?
Post by: metalliqaz on Wed, 01 May 2013, 20:02:18
static.  It remembers.

What he said.
Title: Re: C++ Study Help?
Post by: Lastpilot on Wed, 01 May 2013, 20:05:29
So does that mean that the "= 5" part doesn't matter on the second function call?
Title: Re: C++ Study Help?
Post by: metalliqaz on Wed, 01 May 2013, 20:06:35
Yes, once it is initialized it doesn't get initialized again.
Title: Re: C++ Study Help?
Post by: Lastpilot on Wed, 01 May 2013, 20:07:32
Ah okay I get it. Thanks guys!
Title: Re: C++ Study Help? [solved]
Post by: hashbaz on Wed, 01 May 2013, 20:11:01
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.
Title: Re: C++ Study Help? [solved]
Post by: jalaj on Wed, 01 May 2013, 21:32:20
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
Title: Re: C++ Study Help? [solved]
Post by: metalliqaz on Wed, 01 May 2013, 21:33:37
That is not correct code.