Return two values ​​of a function in c ++

advertisements

This question already has an answer here:

  • Returning multiple values from a C++ function 17 answers

Can I return two values from function one intiger and boolean? I tried to do this in this way but its doesnt work.

int fun(int &x, int &c, bool &m){
        if(x*c >20){
           return x*c;
          m= true;
            }else{
                return x+c;
                m= false;
                }

fun(x, c, m);
    if(m) cout<<"returned true";
    else cout<<"returned false";

        }


You can create a struct which contains two values as its members. You can then return that struct, and access the individual members.

Thankfully, C++ does this for you by the pair class. To return an int and a bool, you can use pair<int,bool>.