Search code examples
c++functionvariablesreturn

Return Multiple Values C++


Is there a way to return multiple values from a function? In a program I'm working on, I wish to return 4 different int variables to the main function, from a separate function, all stats needed to continue through the program. I've found no way to really do this. Any help would be greatly appreciated, thanks.


Solution

  • One solution could be to return a vector from your function :

    std::vector<int> myFunction()
    {
       std::vector<int> myVector;
       ...
       return myVector;
    }
    

    Another solution would be to add out parameters :

    int myFunction(int *p_returnValue1, int *p_returnValue2, int *p_returnValue3)
    {
       *p_var1 = ...;
       *p_var2 = ...;
       *p_var3 = ...;
       return ...;
    }
    

    In the second example, you'll want to declare the four variables that will contain the four results of your code.

    int value1, value2, value3, value4;
    

    After that, you call your function, passing the address of each of your variables as parameters.

    value4 = myFunction(&value1, &value2, &value3);
    

    EDIT : This question has been asked before, flagging this as duplicate. Returning multiple values from a C++ function

    EDIT #2 : I see multiple answers suggesting a struct, but I don't see why "declaring a struct for a single function" is relevant when their are obviously other patterns like out parameters that are meant for problems like this.