Author Topic: C++ Study Help? [solved]  (Read 1581 times)

0 Members and 1 Guest are viewing this topic.

Offline Lastpilot

  • Power stance
  • * Esteemed Elder
  • Thread Starter
  • Posts: 1463
  • Location: Louisiana
C++ Study Help? [solved]
« 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?
« Last Edit: Wed, 01 May 2013, 20:07:50 by Lastpilot »

Offline hashbaz

  • Grand Ancient One
  • * Moderator Emeritus
  • Posts: 5057
  • Location: SF Bae Area
Re: C++ Study Help?
« Reply #1 on: Wed, 01 May 2013, 20:01:37 »
static.  It remembers.

Offline metalliqaz

  • * Maker
  • Posts: 4951
  • Location: the Making Stuff subforum
  • Leopold fanboy
Re: C++ Study Help?
« Reply #2 on: Wed, 01 May 2013, 20:02:18 »
static.  It remembers.

What he said.

Offline Lastpilot

  • Power stance
  • * Esteemed Elder
  • Thread Starter
  • Posts: 1463
  • Location: Louisiana
Re: C++ Study Help?
« Reply #3 on: Wed, 01 May 2013, 20:05:29 »
So does that mean that the "= 5" part doesn't matter on the second function call?

Offline metalliqaz

  • * Maker
  • Posts: 4951
  • Location: the Making Stuff subforum
  • Leopold fanboy
Re: C++ Study Help?
« Reply #4 on: Wed, 01 May 2013, 20:06:35 »
Yes, once it is initialized it doesn't get initialized again.

Offline Lastpilot

  • Power stance
  • * Esteemed Elder
  • Thread Starter
  • Posts: 1463
  • Location: Louisiana
Re: C++ Study Help?
« Reply #5 on: Wed, 01 May 2013, 20:07:32 »
Ah okay I get it. Thanks guys!

Offline hashbaz

  • Grand Ancient One
  • * Moderator Emeritus
  • Posts: 5057
  • Location: SF Bae Area
Re: C++ Study Help? [solved]
« Reply #6 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.

Offline jalaj

  • Posts: 156
Re: C++ Study Help? [solved]
« Reply #7 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

Offline metalliqaz

  • * Maker
  • Posts: 4951
  • Location: the Making Stuff subforum
  • Leopold fanboy
Re: C++ Study Help? [solved]
« Reply #8 on: Wed, 01 May 2013, 21:33:37 »
That is not correct code.