Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression for struct creation

Tags:

c

syntax

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)?

like image 886
nils Avatar asked Jul 18 '10 16:07

nils


1 Answers

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.

like image 118
nos Avatar answered Oct 29 '22 17:10

nos