结构创建的表达式

nil*_*ils 3 c syntax

在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 };
}
Run Code Online (Sandbox Code Playgroud)

f是有效的,g不是.同样适用于函数调用:

float distance(Point a, Point b) {
    return 0.0;
}
int main() {
    distance({0, 0}, {1, 1})
}
Run Code Online (Sandbox Code Playgroud)

是否有可能在不必使用额外的临时变量的情况下创建这些结构(我猜这将被编译器优化,但可读性也很重要)?

nos*_*nos 9

使用C99编译器,您可以执行此操作.

Point g(int x) {
    return (Point){ .x = x, .y = x*x };
}
Run Code Online (Sandbox Code Playgroud)

你的电话distance会是:

distance((Point){0, 0}, (Point){1, 1})
Run Code Online (Sandbox Code Playgroud)

他们被称为复合文字,例如参见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获取一些信息.