In C++, how can I have a function return multiple values?
In C++, how can I have a function return multiple values?
There are two options. Either pass references/pointers as arguments (preferable) or create a struct that has all the variables you'd like and return it (not preferable). For example:Code:struct UglyStruct { int some_thing; char another_thing; string foo_bar; }; UglyStruct some_func() { UglyStruct us; us.some_thing = 1234; us.another_thing = '?'; us.foo_bar = "Blah"; return us; } void some_func(int &int_ref, char &char_ref, string *ptr_string) { int_ref = 2468; char_ref = '!'; if (ptr_string != 0) *ptr_string = "*Cough cough*"; }
Last edited by LuckY; 08-23-2005 at 10:15 AM.
Of course, pointers.
My brain is melting.
Thanks.
I wouldn't call the struct ugly. One might say that the reference or pointer parameters are confusing in that it is not immediately apparent that the argument will be modified by the function. I use both techniques and IMO both have their place. Neither is really preferable in general.
Of course it all depends entirely on context. There absolutely are cases where an individual will use a struct to group multiple variables together (I've done exactly that many a time). In fact, there are some cases where it's explicitly required (such as passing multiple params as an LPARAM in a Windows message or a void* in a child thread, for example), but I personally feel it is not a very attractive practice to create structs on-the-fly for simple situations where the struct will strictly be used for returning a pair of values. As an example, I would consider it "ugly" to do something like this:when you could do this:Code:struct RetData { string str; int length; }; RetData str_copy(const string &src) { RetData ret; ret.str = src; ret.length = src.length(); return ret; }or this:Code:int str_copy(string &dest, const string &src) { dest = src; return dest.length(); }It's not that one is necessarily better than the other. Rather, in such a simple case, I feel that creating a struct strictly to return a pair of values (not to mention all the potential temporary variables that could be created) is overkill. But that's just me.Code:void str_copy(string &dest, int &length, const string &src) { dest = src; length = dest.length(); }
Last edited by LuckY; 08-23-2005 at 01:06 PM.
Boost's tuple has been added to TR1 and will be part of the next standard. Using that (or std::pair) would be preferable to your own handwritten structs if all you want to do is hold multiple values. For expensive to copy objects of course the pass-by-reference version saves the copy.