Lets imagine that we have function that should return two return values.
For instance we have some function that returns char*
and its length. Char is allocated within that particular function.
I can imagine following ways of doing that:
int foo(char **result); // Passing pointer to char*, returning int
char* bar(int *len); // Passing pointer to int, returning char*
struct char_and_len foobar(); // Returning struct that contains both values
Is there any other ways to implement multiple values and what's the most effective way to do that?
I'd really appreciate detailed explanation, considering performance, memory alignment or any other hidden C feature.
There are two cases here. If you are working in a codebase/framework (e.g. Glib) that has a standard string struct used throughout the entire application, then use your third option:
struct string function();
If your codebase is not using one standard struct everywhere for strings, I would advise against using a struct. The hassle of converting back and forth is not really worth it.
Otherwise, the convention (at least that I've seen) is to return the char*
and have the length as a pointer parameter:
char* function(int* length);