Effective Multiple Return Values

Let's imagine that we have a function that should return two return values. For example, we have some function that returns char*its length. Char stands out inside this particular function.

I can imagine the following ways of doing this:

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

Are there other ways to implement multiple values ​​and the most efficient way to do this?

I would really like the detailed explanation, given performance, memory alignment, or any other hidden C function.

+4
source share
7 answers

. / (, Glib), , , :

struct string function();

, . .

( , ) char* :

char* function(int* length);
+3

:

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

, , :

struct char_and_len foobar();

, , ​​ .

+1

struct:

typedef struct {
    char *strings[2];
} RetType;

RetType func()
{
    return (RetType){ { "foo", "bar" } };
}

C, :

void func(char *strings[2])
{
    strings[0] = "foo";
    strings[1] = "bar";
}

- ( , ):

char *func(char **outparm)
{
    *outparm = "foo";
    return "bar";
}

, , const -.

+1

void foobar(struct char_and_len*);

:

  • return value/out .
  • , , . .
  • . .
  • , , struct char_and_len ( , ),
+1

.

, , , . , C , , , . . char* , , . , .

...

, , , , ( ) , , . , , ? , , ? , .

+1

- . C , . - , .

, , void.

0

C "" . , , , . , , . .

( Pascal VB ..). C . ++ ( , ).

, , , , :

char * bar (int * lenP); //

now you have the result of a function that can return two results:

as if it were defined as pseudo syntax (s, l) = bar ();

Additionally you can also use:

void bar (char * * s, int * lenP); // this case applies equally to arguments too.

In C ++, I would use a reference approach, because being practically the same from a practical point of view (what the processor does), it is easier for the programmer.

0
source

All Articles