How do I return multiple variables from a C++ function?

Asked By 230 points N/A Posted on -
qa-featured

Hi,

I am learning to code with C++. I was wondering if I can return multiple variables from a C++ program, instead of declaring as global, if possible. Suppose I have a function that works on 3 integers; do some process on them, I want 3 of them to be returned.

SHARE
Best Answer by Britney Camden
Answered By 0 points N/A #101437

How do I return multiple variables from a C++ function?

qa-featured

You can't return multiple variables from a function. What you can:

Return an array pointer.

Return a custom data type(struct) to contain the return variables.

Return a STL container.

Answered By 230 points N/A #101438

How do I return multiple variables from a C++ function?

qa-featured

Thanks. Looks like returning an array would be easier. But I couldn’t help it. Can anyone help me in writing the function please?

Answered By 0 points N/A #101439

How do I return multiple variables from a C++ function?

qa-featured

It’s easy to return an array in C++. You just need to use pointers with the return type of your function and you will need to  declare an array (also with pointer) to which the function will return the object. The syntax will be like this:

Int* function()

{

return a;               //  — > (Here a is an array);

}

Int main()

{

b=function();              // (here b is an array);

return 0;

}

I hope it helps

Answered By 230 points N/A #101440

How do I return multiple variables from a C++ function?

qa-featured

Thanks for the response mate but something went wrong. My function returns a bizarre output.

Answered By 0 points N/A #101441

How do I return multiple variables from a C++ function?

qa-featured

Would u like to post your code here so that I can investigate the bugs there?

Answered By 230 points N/A #101442

How do I return multiple variables from a C++ function?

qa-featured

#include <iostream>

using namespace std;

int* function()

{

    int a[6]                              //=new int[6];

    a[0]=1;

    a[1]=2;

    a[2]=3;

    a[3]=4;

    a[4]=5;

    a[5]=6;

    return a;

}

int main()

{

    int *b;

    b=function();

    for(int i=0;i<6;i++) cout<<b[i]<<endl;

    return 0;

}

Best Answer
Best Answer
Answered By 0 points N/A #101443

How do I return multiple variables from a C++ function?

qa-featured

Replace the line “int a[6]” with “int *a=new int[6]”. You need to change this statement because your array “a” may be corrupted due to dynamic memory allocation.

Answered By 230 points N/A #101444

How do I return multiple variables from a C++ function?

qa-featured

Thank you.. thank you. Thank you.. thank you. Thank you.. thank you.

Related Questions