Besides using function to return values, you can have a pass-by-pointer or pass-by-reference parameter into the function to make changes on the input variables inside.
Returning a struct out of a function implies more operations needed as a pass-by-value will invoke possibly default constructor,copy constructor,assignment operator which is costly.
If you want efficiency and return a pointer to struct out of a function, you pray the calling program will dispose of that faithfully.
So I would prefer to go back to pass in parameters to function approach.
void f(int& x, int & y)
{
x = 10;
y = -10;
}
#include <iostream>
int main()
{
int a(0);
int b(0);
f(a, b);
std::cout << "a " << a << "\tb " << b << '\n';
return 0
}
Returning a struct out of a function implies more operations needed as a pass-by-value will invoke possibly default constructor,copy constructor,assignment operator which is costly.
You can only return a single value from a function; however, you can return a address in memory that contains a user defined amount of bytes. I encourage you to pass by reference though, for unnecessary memory managment should always be avoided
1 2 3 4 5 6
int *return_array_dyn(void) {
int *arr = newint[2];
arr[0] = 1;
arr[1] = 2;
return arr;
}
@jloundy That may not be such a great idea. Then it becomes the caller's responsibility to clean up after the callee (using delete). Return by value and let RVO do the rest http://en.wikipedia.org/wiki/Return_value_optimization
(In other words use something other than an intrinsic array, e.g. std::pair, etc and then return it by value. The compiler is permitted by the C++ standard to remove the copy operation invoked.)
@Xander314, Hence why I encouraged other methods since "unecessary memory managment should always be avoided" ; however, he should know that you can return memory locations.
@shacktar
No, it doesn't, but your answer is no more succinct than many of the answers in the existing thread. You'd know that if you had bothered to read it.
Besides yours, mine was the only one with a code example up to that point. Of course I had read the thread; I felt like it was lacking a succinct code example, though, and judging by the OP's reaction, it was appreciated. And by "many of the answers in the existing thread", you meant the previous two before my post? And if by "existing thread" you mean the one you posted to, then my code example was more easily digestible for beginners like the OP. I (and anyone for that matter) shouldn't have to defend their responses in a thread, even if similar responses were given previously.