Gina Cucchiara
Gina Cucchiara

Reputation: 39

c++ trying to change local variable in function

im learning functions and I have been trying to call my last value for total from my function (so the total that is labeled "total so far") when going through the for loop (which print out 36 when using 8 as the test number) to print out 36 again in my main function at "your total is"

I understand it is not printing out 36 because in the function I am treating total as a local variable and I think I need to use it as a global or static but I'm not sure

also when I did attempt to make it a static I'm not sure I did it right I wrote static in front of both my total variables when defining them

#include <iostream>
using namespace std;

int sum(int count);

int main()
{
    int count;
    double num, total;

    cout << "Please enter a number: ";
    cin >> num;

    for (count = 1; count <=num;  count = count + 1)
    {
        sum(count);
    }

    cout << "Your total is: " << total << endl;
    return 0;
}

int sum(int count)
{
    double total;
    total = total + count;
    cout << "Current number: " << count << endl;
    cout << "Total so far: " << total << endl;
}

Upvotes: 3

Views: 1670

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595712

total is uninitialized in both main() and sum(), so any results you get are indeterminate.

And indeed, total inside of sum() is local to sum(), and total in main() is local to main(). Any changes sum() makes to its own total do not affect the total in main().

You should change sum() to take total from main() as an input parameter passed by pointer/reference so that sum() can modify its value:

#include <iostream>

using namespace std;

void sum(double &total, int count);

int main()
{
    int count, num;
    double total = 0.0;

    cout << "Please enter a number: ";
    cin >> num;

    for (count = 1; count <= num; ++count)
    {
        sum(total, count);
    }

    cout << "Your total is: " << total << endl;
    return 0;
}

void sum(double &total, int count)
{
    total += count;
    cout << "Current number: " << count << endl;
    cout << "Total so far: " << total << endl;
}

Live Demo

Upvotes: 3

Joseph D.
Joseph D.

Reputation: 12174

total in main() and total in sum() are different variables for they have different block scope.

int sum(int count) {
   // such a silly pass-through implementation if you want to calculate "total"
   // do something with count
   return count;
}
// in main
double total = 0;
total += sum(count);

Upvotes: 1

Related Questions