Structure expression

Is it possible to create inline structures in C?

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 };
}

freally gnot. The same applies to function calls:

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

Is it possible to create these structures without the need to use an additional temporary variable (which will be optimized by the compiler, I think, but an indicator of readability too)?

+3
source share
2 answers

With the C99 compiler you can do this.

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

Your call distancewill look like this:

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

, ., , 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 .

+8

. () C.

-1

Source: https://habr.com/ru/post/1755197/


All Articles