Skip to main content

Command Palette

Search for a command to run...

C++ Returning Multiple Values from a Function

Published
•2 min read•View as Markdown
C++ Returning Multiple Values from a Function
T

I am an aspiring software engineer from the University of Belize, currently pursuing a Bachelor's degree in computer science. I am diving headfirst into the endeavor of writing and focused reading. Therefore, this blog is an outlet to grow those skills while benefiting those who may find my content helpful. I write about topics related to software, development, design, and personal growth from the perspective of an INTJ.

Note: You can skip to the code at the bottom of the page under the Function Call Section.

Note: The method explained does not work when returning values of different types. You will need to utilize other structures such as a vector.

Note: It is best that you have some understanding of pointers and the allocation of static variables, and dynamic variables.

References are provided at the bottom of the page.

The Function Signature

In this example, I pass three integer variables into a function and return three integers within an array.

The return type of the function must be a pointer since an integer array is used to save the values we want to return.

Therefore, the function signature looks like this:

int* myfunction(int num1, int num2, int num3){
//code....
}

Function Definition

Next, we create an integer array in the function definition to hold the values we want to return.

Since C++ does not allow you to use local variables outside the scope of the function that it is in, this array must be declared as a static array.

You can assign the values gotten in the function parameters to different positions in the array for this example.

The function definition should look like this:

int* myfunction(int num1, int num2, int num3){
    static int arr[3]; //initialize integer array
    arr[0] = num1;
    arr[1] = num2;
    arr[2] = num3; //assign values

    return arr;
}

The Function Call

Assign the return values of the function to a pointer variable that is of the type given to the static array.

To access the values from the pointer variable, you need to dereference them wherever you want to use the value in the array. Observe the following code:

#include <iostream>
using namespace std;

int* myfunction(int num1, int num2, int num3){
    static int arr[3]; //initialize integer array
    arr[0] = num1;
    arr[1] = num2;
    arr[2] = num3; //assign values

    return arr;
}

int main()
{
    int* get_array = myfunction(4, 5, 6); //function call
    cout<<"1st number is "<<*(get_array + 0)<<endl;
    cout<<"2nd number is "<<*(get_array + 1)<<endl;
    cout<<"3rd number is "<<*(get_array + 2)<<endl;//printed output

    return 0;
}

References:

Appendix

Here is where I encountered a similar problem in one of my projects:

Thank you for reading and I hope this helps.