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.
char*
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.
. / (, Glib), , , :
struct string function();
, . .
( , ) char* :
char* function(int* length);
:
void foo(char **result, int *len);
, , :
struct char_and_len foobar();
, , .
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 -.
const
void foobar(struct char_and_len*);
struct char_and_len
.
, , , . , C , , , . . char* , , . , .
...
, , , , ( ) , , . , , ? , , ? , .
- . C , . - , .
, , void.
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.