Can one functon gets a value from other function and use it?

Aug 21, 2014 at 8:00am
Hi,
is there any way to get one function to return a value and other function to use it? Thanks.

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
#include <iostream>

using namespace std;

int Square (float a)
{
    float b;
    b = a * a;
    return b;
}

int Sum (float f, Square ())
{
    float h;
    h = f * Square () / 2;
    return h;
}
int main()
{
    float c, d, e;
   cout << "Enter the breadth in cm: \n" << endl;
   //cin >> c;
   c = 60;
   cout << "Enter the thickness in cm: \n" << endl;
   //cin >> d;   
   d = 4.5;
   e = Sum (c, Square (d));
   cout << "The sum is " << e << ".\n" << endl;
   return 0;
}

i know i can just write the program this way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main()
{
    float a, b, c;
   cout << "Enter the breadth in cm: \n" << endl;
   //cin >> a;
   a = 60;
   cout << "Enter the thickness in cm: \n" << endl;
   //cin >> b;   
   b = 4.5;
   c = a * (b * b) / 2
   cout << "The sum is " << e << ".\n" << endl;
   return 0;
}

but i'm interested to know how to make one function gets a value from another function and use it.
Aug 21, 2014 at 8:12am
You have:
int Square (float a);
and you use it in
e = Sum (c, Square (d));
The Square is evaluated before the Sum, and therefore, you could have written:
1
2
int s = Square(d);
e = Sum (c, s);

Therefore the Sum should accept int as second parameter.

PS. Your Square converts a float into an int. You should reconsider that.
Aug 21, 2014 at 8:52am
Thanks.
just let me re-confirm what you had say,
in order for Sum to use the return value from Square, the return value has to go back to main.
Is there anyway for Sum to get the value straight from Square?
Aug 21, 2014 at 10:48am
You already had the "straight", even though "via main":
e = Sum( c, Square(d) );

You could do:
1
2
3
float Sum( float a, float b ) {
  return a + Square( b ); // like writing: return a + b * b;
}

That means that Sum will always square something

Sum could take a third parameter: a function pointer. Then the caller of Sum would decide which function the Sum will call (but the signature of possible functions is fixed).
Aug 21, 2014 at 11:14pm
Thanks. I think i understand.
Topic archived. No new replies allowed.