Technically a function can only return one value. So if you ever get asked if it's possible tell the interviewer that you can only ever return one value but that value could be a composite type.
If it's C++ then
std::pair
is quick solution. Unfortunately pair's members are imaginatively named
first
and
second
so you keep having to remember what they mean. For this reason it can be an idea to declare your own composite type to return with better names.
Cheers,
Ash
PS: As this question has returned to the top of the pile I thought I'd add this...
When you return a structure (the composite type I alluded to above) EVERYTHING in the structure is copied. And I mean EVERYTHING. And that happens in C and C++ (if you don't have a copy constructor). So you can write things like this (in C, don't try it in C++, it's not the done thing):
#include <stdio.h>
struct message
{
char text[128];
};
struct message return_a_message()
{
struct message msg = { "Oo, what's this then?" };
return msg;
}
int main()
{
struct message msg = return_a_message();
printf( "%s", msg.text );
return 0;
}
My usual caveat applies here - I'm not in practise with C so someone that knows what they're talking about may be able to pick great holes in it. It might be poisoned by Microsoftisms as well.
Interestingly the VC++2010 compiler doesn't create a temporary to return the object, so it looks like C++ style NRVO is kicking in here. Cool!
PPS: I first saw this technique in "Expert C Programming" by Peter van der Linden sometime in the late 90s. If you're a C programmer go and buy a copy. Oh and ignore the C++ chapter it's well out of date and not particularly knowledgeably written (although amusing and thought provoking in places). Ah, screw it, read that chapter as well.