Clayton C.
Clayton C.

Reputation: 881

Persisting variables outside scope of a function

This is part of a debugging assignment that I've been stuck on for days. I'm not as much looking for an answer as much as I'm looking for where to look to find the answer.

I have a function that takes an int as a parameter, and the test uses that function to calculate the sum of the range (0,n]. My problem is that I am new to C++ and have exhausted my knowledge of where to look to solve this. Any help would be greatly appreciated.

Also, it goes without saying that I cannot modify the test file.

Header.h

bool getNum(int n);

Header.cpp:

bool getNum(int n)
{
    n = n + 1;

    if (n < 10)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Test.cpp

int n = 0;
int sum = 0;

while (getNum(n) && n)
{
    sum += n;
}

CHECK(sum == 45);

My problem is that I have no way of getting n to be true to pass the logical &&, so the test never visits the inside of the while loop.

Upvotes: 0

Views: 251

Answers (1)

cigien
cigien

Reputation: 60238

You can change the value of an argument to a function, by taking that argument as a reference:

bool getNum(int &n)  // note the reference parameter
{
  // changes to n are visible to the caller of this function
}

You have to change the declaration of getNum to match as well, of course.

Note that there is no change to the calling code.

Here's a demo of a working example.

Upvotes: 2

Related Questions