Monday, 30 June 2008

How to return multiple variables??

In C++, every function will have some return value, however, the number of permitted return value is one.

For example,

int myfunc()
{ int a, b;

a=3; b=4;

return a,b;
}

will cause trouble since the calling function will not know which value is returned...

Then how we return multiple values like described above??

We may define a structure data, for example,

typedef struct Mystruct
{ int a,
int b
} MYSTRUCT;

in the header file,

then in the cpp file,

we define the function as MYSTRUCT type:

MYSTRUCT myfunc()
{
MYSTRUCT mystruct;

mystruct.a=3;
mystruct.b=4;

return mystruct;
}

Here we go!

We may define another MYSTRUCT type data and the returned value would be transfered to that data by the calling function.

Cheers!

No comments: