Passing values from a function to another function

Viewed 139

I'm new in C++ programming world and I have not understood yet if it's possible (and how) to use an output from a function as input to another function.

#include <iostream>
using namespace std;

int func(int l, int m) {
    int x = l * m;
    return x;
}

int code(x?) {
    ...
}

I would like to use output from func (the value x) as an input for code. Is it possible? How could I do that?

Thanks for the help

EDIT 1:

Really thanks for the answers. Is it possible also to pass values between functions using pointers?

5 Answers

Functions only "have" values while they are executed.
You can either call the first from the second funtion,
or call the first function, read the return value into a variable and give that value as parameter to the second,
or call the second and give one of its parameters directly as return value from a call to first function.

Here are some examples of the three options, using 1,2,3 as arbitrary integers.

Variant 1:

int func(int l, int m) {
    int x = l * m;
    return x;
}

int code(void) {
    int ValueFromOtherFuntion=func(1,2);
    return 3;
}

Variant 2:

int func(int l, int m)
{
    int x = l * m;
    return x;
}

int code(int XfromOtherFunction)
{
    return 3;
}

int parentfunction(void)
{
    int ValueFromOtherFuntion=func(1,2);
    return code(ValueFromOtherFunction);
}   

Variant 3:

int func(int l, int m)
{
    int x = l * m;
    return x;
}

int code(int XfromOtherFunction)
{
    return 3;
}

int parentfunction(void)
{
    return code(func(1,2));
}   

Yes, what you are looking for is called function composition.

int sum(int a, int b)
{
    return a + b;
}

int square(int x)
{
    return x*x;
}

int main()
{
    std::cout << square(sum(5, 4)); //will calculate (5+4)squared
}

When you write the functions, assume that you already have all the input and proceed just writing what you want that function to do.

As to when you use that function, use "nested functions" or a function inside a function as such:

code(func(l, m));

Function func will execute first and return the value x, thus leaving you with code(x) which will execute after. Its like pealing an onion: one layer to the other.

#include <iostream>

int func(int l, int m) {
    int x = l * m;
    return x;
}

void code(int x) { // argument type is the same as the return type of func
  std::cout << x;
}

int main (){
   int result = func(1 ,2); // either store it
   code(func(1, 2));        // or pass it directly.
   std::cout << result;
   return -1;
}

You can call it in your main function (or in any other within scope for what matters):

code(func(l,m))

Related