Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effective multiple return values [duplicate]

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.

like image 275
Sigurd Avatar asked Mar 22 '23 03:03

Sigurd


2 Answers

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);
like image 143
Linuxios Avatar answered Apr 02 '23 22:04

Linuxios


Another way:

void foo(char **result, int *len);

The worst in my opinion is:

struct char_and_len foobar();

The one I prefer is the one I showed you, because I don't like to mix return values in both arguments and effective return.

like image 45
bolov Avatar answered Apr 02 '23 21:04

bolov