No of visitors who read this post: 566
Category: C++
Type: Question
Author: Booker
Your rating: None Average: 5 (23 votes)

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.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

#

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.

<><><><><><><><><>

I am here. As always.

#

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

#

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

<><><><><><><><><>

I am here. As always.

#

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

#

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

<><><><><><><><><>

I am here. As always.

#

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

}

# (Solution Accepted)

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.

<><><><><><><><><>

I am here. As always.

#

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