How to do that? I watched on Google and I found a lot of this but I dont understand. If someone can post example and explanation.
Thanks!
5 replies to this topic
#1
Posted 01 February 2012 - 06:47 AM
|
|
|
#2
Posted 01 February 2012 - 08:31 AM
There is no way to return multiple values via a return statement, BUT there are ways to get around this limitation. In C, you can use reference parameters that could be changed in the called function. In C++, you can also use reference, or even make a class for a result that gets returned from the function.
#3
Posted 01 February 2012 - 08:32 AM
lespauled said:
There is no way to return multiple values via a return statement, BUT there are ways to get around this limitation. In C, you can use reference parameters that could be changed in the called function. In C++, you can also use reference, or even make a class for a result that gets returned from the function.
Can you give me an example?
#4
Posted 01 February 2012 - 08:46 AM
void foo(int &i) // <= notice the reference to i
{
i++;
cout << i << endl;
}
int main()
{
int i = 0;
cout << i << endl;
foo(i);
cout << i << endl;
return 0;
}
{
i++;
cout << i << endl;
}
int main()
{
int i = 0;
cout << i << endl;
foo(i);
cout << i << endl;
return 0;
}
#5
Posted 01 February 2012 - 09:42 AM
If you want to avoid functions having side effects on reference variables, you can also declare a struct to contain multiple values of interest. Then, your function would create an instance of this struct and assign its values, and return the single object, which itself contains multiple values.
Example:
There you go. Two values returned from a function, wrapped in a struct.
Example:
typedef struct Multival_struct {
int value_a;
int value_b;
} Multival;
Multival foo() {
Multival val;
val.value_a = 5;
val.value_b = 10;
return val;
}
int main() {
Multival answer;
answer = foo();
printf("%d ", answer.value_a);
printf("%d", answer.value_b);
}
// The above would print out:
// 5 10
There you go. Two values returned from a function, wrapped in a struct.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.
– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid
#6
Posted 02 February 2012 - 04:10 AM
Beside reference you can also use pointer.
It would look like :
It would look like :
#include <iostream>
using namespace std;
void f( int *ptr) {
cout << *ptr << endl;
*ptr = 120;
cout << *ptr<< endl;
}
int main(int argc, char *argv[])
{
int i=5;
f(&i);
cout << i << endl;
}
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









