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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With