1

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";

        }

2 Answers2

3

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>.

therainmaker
  • 4,253
  • 1
  • 22
  • 41
  • 1
    I once heard a Scott M. talk where he strongly suggested not to use a `pair` whenever you know what it actually is and I completely agree. A `struct { int day;int month }` is always preferable to a `pair` or a `struct { int counter;bool expired }` is better than a `pair`. – 463035818_is_not_an_ai Dec 10 '15 at 13:25
2

You can return a struct that contains some values.

struct data {
    int a; bool b;
};


struct data func(int val) {
    struct data ret;
    ret.a=val;
    if (val > 0) ret.b=true;
    else ret.b=false;
    return ret;
}


int main() {
    struct data result = func(3);
    // use this data here
    return 0;
}
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 1
    No need for `struct data` aside from the declaration. C++ ain't C, you know. Also close the `struct` declaration with `;`. – Bathsheba Dec 10 '15 at 12:54