Home > Net >  I want to know why only b is returned when I do like return(a,b)
I want to know why only b is returned when I do like return(a,b)

Time:10-10

#include <iostream>
using namespace std;
int addmult(int ii, int jj);

int main() {
    int i = 3, j = 4, k, l;
    k = addmult(i, j); // 12
    l = addmult(i, j); // 12
    cout << k << "\n" << l; // 12 12 
}

int addmult(int ii, int jj) {
    int kk, ll;
    kk = ii   jj; // 7
    ll = ii * jj; // 12
    int a = (kk, ll);
    cout << "a = " << a << endl; // 12
    return a;
}; 

Hello, I want to know why the output result is 12 when I return like that. I returned (val1, val2) like that, but I can find only b is returned.

CodePudding user response:

When you have an expression (kk, ll) it does not create a tuple. Rather it evaluates both expressions and returns the value of ll. So the addmult function only ends up returning that value.

There is the std::pair data type in the STL which would let you return two values.

std::pair<int, int> addmult(int ii, int jj) {
    int kk, ll;
    kk = ii   jj; // 7
    ll = ii * jj; // 12
    std::pair<int, int> a {kk, ll};
    cout << "a = " << a.first << ", " << a.second << endl;
    return a;
}

CodePudding user response:

If you want to have multiple return values and readable code. Then define your own return type as a struct. (For pairs I always end up having to look back what first and/or second mean.)

#include <iostream>

// declare a struct that can hold all your return values
// and give them readable names.
struct addmult_result_t
{
    int addition;
    int multiplication;
};

// do your calculation and return the result
addmult_result_t addmult(int ii, int jj) 
{
    return addmult_result_t{ii   jj, ii * jj};
}

int main()
{
    int i = 3, j = 4;
    auto result = addmult(i, j);

    std::cout << "addition = " << result.addition << "\n";
    std::cout << "multiplication = " << result.multiplication << "\n";

    return 0;
}
  • Related