Asked By
Booker
230 points
N/A
Posted on - 05/19/2011
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.
How do I return multiple variables from a C++ function?
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
Booker
230 points
N/A
#101438
How do I return multiple variables from a C++ function?
Thanks. Looks like returning an array would be easier. But I couldn’t help it. Can anyone help me in writing the function please?
How do I return multiple variables from a C++ function?
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
Booker
230 points
N/A
#101440
How do I return multiple variables from a C++ function?
Thanks for the response mate but something went wrong. My function returns a bizarre output.
How do I return multiple variables from a C++ function?
Would u like to post your code here so that I can investigate the bugs there?
Answered By
Booker
230 points
N/A
#101442
How do I return multiple variables from a C++ function?
#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;
}
How do I return multiple variables from a C++ function?
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
Booker
230 points
N/A
#101444
How do I return multiple variables from a C++ function?
Thank you.. thank you. Thank you.. thank you. Thank you.. thank you.