function returns

Curious: Can a function return more than one argument?
Functions can take several argument but they can return only one value.
You can return a container object or something similar which contains more values.
C++0x will have tuple which can contain multiple values of different types
1
2
3
4
5
6
int* foo() {
    int x[3] = {
       0x28, 0x29, 0x2a
    };
  return x;
}


1
2
3
4
5
6
7
8
9
10
11
struct A {
   int a, b, c;
};

A foo() {
  A st_a;
    st_a.a = 0x28;
    st_a.b = 0x29;
    st_a.c = 0x2a;
  return st_a;
}


but not as so
Theoretcial code:

1
2
3
{int, char, char} foo() {
  return {0, 'a', 'b'}
}
Last edited on
Hi!

Is this code legal??

1
2
3
4
5
6
int* foo() {
    int x[3] = {
       0x28, 0x29, 0x2a
    };
  return x;
}


Because of array "x" is created on stack! And it seems to work properly but the returned array "x" is released memory area in my opinion. In addition if you refer this area latter you can get a pretty crash.

Please confirm or deny me.
Is this code legal??

Legal but does not work.
I suggest you using standard containers, they are more flexible than automatic arrays and easier to manage than dynamic arrays
eg:
1
2
3
4
5
6
std::vector<int> foo()
{
    int x[] = { 0x28, 0x29, 0x2a };
    std::vector<int> v ( x, x+3); // C++0x will allow std::vector<int> v = { 0x28, 0x29, 0x2a };
    return v; // return a copy of v
}
Last edited on
ok.
cant functions change more than one variable if it was pointer reference or just plain references

any c++ gurus out there can prob show you a good example...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

void multiplication(int *p, int *pp, int *ppp);

int main()
{
int a = 4; b = 23, c = 123;
multiplication(&a, &b, &c);

cout << a << endl << b << end << c << endl;
return 0;


void multiplication(int *p, int *pp, int *ppp)
{
*p = *p + *p;
*pp = *pp + *pp;
*ppp = *ppp + *ppp;
}


I think that works....
Last edited on
Here is an example
1
2
3
4
5
6
7
8
9
10
11
12
13
void set_argument_to_5 ( int &number )
{
    number = 5;
}


int main()
{
   int x = 2;
   // x == 2
   set_argument_to_5 ( x ); // the parameter 'number' is a reference so all the changes that affect 'number' in the function body, will affect 'x' as well
   // x == 5
}
See http://www.cplusplus.com/doc/tutorial/functions2/ for a detailed explanation
Topic archived. No new replies allowed.