Passing a variable from one function to another

So i'm currently experiencing some problems passing one variable to my main. This is what I got so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;

int main() {

   double x, y;

   double Total(double, double);
   void readTotal(double);

   cout << "Enter value of x: ";
   cin >> x;

   cout << "Enter value of y: ";
   cin >> y;

   Total(x, y);
   readTotal(TotalofValues);

   system("pause");
   return 0;
}

double Total(double x, double y) {

       double TotalofValues = 0;
       TotalofValues = x + y;
}

void readTotal(TotalofValues) {

       cout << "Your total is: " << TotalofValues << endl;
}


This is just an example I wrote up in 5 minutes, but how would I reference TotalofValues back to my main? could I use Total as a variable (even though it is used as a function) and that would reference back to the int main() function? I'm just unsure on how to get it from one function back to main and then send it to another function.. With the program I got now, I can't do a function within a function because it would not meet the criteria.

All help will be appreciated.

Last edited on
This won't compile.

What a variable is named in a function or a parameter list has no bearing on what a variable with the same value is called in another scope.

incorrrect:
1
2
3
4
5
double Total(double x, double y) {

       double TotalofValues = 0;
       TotalofValues = x + y;
}


You tell the compiler you're going to return a value of type double. You do not.

correct:
1
2
3
double Total(double x, double y) {
       return x+y ;
}


incorrect:
1
2
3
4
void readTotal(TotalofValues) {

       cout << "Your total is: " << TotalofValues << endl;
}


correct:
1
2
3
void printTotal(double total) {
       cout << "Your total is: " << total << endl;
}


incorrect:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main() {

   double x, y;

   double Total(double, double);
   void readTotal(double);

   cout << "Enter value of x: ";
   cin >> x;

   cout << "Enter value of y: ";
   cin >> y;

   Total(x, y);
   readTotal(TotalofValues);

   system("pause");
   return 0;
}


correct:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double Total(double, double) ;
void printTotal(double) ;

int main() {
   double x,
   cout << "Enter value of x: ";
   cin >> x;

   double y ;
   cout << "Enter value of y: ";
   cin >> y;

   double total_xy = Total(x, y);
   printTotal(total_xy);

   system("pause");
   return 0;
}
Topic archived. No new replies allowed.