Multiple return values in C at the cost of one weird input parameter
github.com
github.com
I suppose the point is to declare a tuple directly as a return type without a typedef. Then, to return a value, use 'typeof' to declare a return variable of that anonymous type. So, the whole point is to avoid a typedef, I think:
typedef struct { int x; int y; } foo_result_t;
foo_result_t foo(int a, int b) {
return (foo_result_t){ a*a, a/b };
}
int main(void) {
foo_result_t a = foo(40,2);
}
Instead of typedef, use typeof and __auto_type. Without the bloat: struct { int x; int y; } foo(int a, int b)
{
typeof(foo(a,b)) out = { a*a, a/b };
return out;
}
int main(void) {
__auto_type a = foo(40,2);
}
It is a bit underwhelming. But it tought me something: I did not know GCC's (and Clang's?) __auto_type extension (new since gcc 4.9, apparently). It looks great for compiler specific magic macros! :-)What am I missing?
struct Foo foo = return_foo();
becomes struct Foo foo;
return_foo(&foo);
That said, the ability to pass, return, and assign structures by value seems to be one of the lesser-known features of C, so this serves as a good example.By the way, if you do C programming and haven't, read 21st Century C:
return out;
(void)zero;
instead of the whole preprocessor magic for clang?And while we're taking suggestions, use a named struct, that keeps you from making up a new type for every case.
- Step 2 post on HN
- Step 3 ???
- Step 4 Enjoy
it's a demonstration of returning a struct by value...
how is this...
1. multiple return values? 2. costing one "weird input parameter"? 3. worthy of a front-page mention?