tags:

views:

85

answers:

2

Is is possible in C to create structs “inline”?

typedef struct {
    int x;
    int y;
} Point;
Point f(int x) {
    Point retval = { .x = x, .y = x*x };
    return retval;
}
Point g(int x) {
    return { .x = x, .y = x*x };
}

f is valid, g not. Same applies to function calls:

float distance(Point a, Point b) {
    return 0.0;
}
int main() {
    distance({0, 0}, {1, 1})
}

Is it somehow possible to create these structs without having to use the extra temporary variable (which will be optimized away by the compiler i guess, but readability counts too)?

A: 

In a word no. Auto-creation of (implied) types and function argument de-structuring is not supported in C.

bjg
Outdated, see C99.
R..
@R.. Fair enough given C99-supporting compilers are now ubiquitous.
bjg
+6  A: 

With a C99 compiler, you can do this.

Point g(int x) {
    return (Point){ .x = x, .y = x*x };
}

Your call to distance would be:

distance((Point){0, 0}, (Point){1, 1})

They're called Compound literals, see e.g. http://docs.hp.com/en/B3901-90020/ch03s14.html , http://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Compound-Literals.html , http://home.datacomm.ch/t_wolf/tw/c/c9x_changes.html for some info.

nos
+1 just to complete your answer a bit. This is called a *compound literal* and it is equivalent to the function `f`: a temporary *anonymous* variable is implicitly created on the stack that has the same scope rules as if it would be declared explicitly.
Jens Gustedt
thx, great to see, that C++ has that too
nils