【问题标题】:Expression for struct creation结构创建表达式
【发布时间】:2010-07-18 16:54:18
【问题描述】:

是否可以在 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 };
}

f 有效,g 无效。同样适用于函数调用:

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

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

【问题讨论】:

    标签: c syntax


    【解决方案1】:

    使用 C99 编译器,您可以做到这一点。

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

    您对distance 的电话是:

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

    它们被称为复合文字,参见例如http://docs.hp.com/en/B3901-90020/ch03s14.htmlhttp://gcc.gnu.org/onlinedocs/gcc-3.3.1/gcc/Compound-Literals.htmlhttp://home.datacomm.ch/t_wolf/tw/c/c9x_changes.html 了解一些信息。

    【讨论】:

    • +1 只是为了完成您的答案。这称为复合文字,它等效于函数f:在堆栈上隐式创建一个临时匿名变量,其范围规则与它相同将被显式声明。
    【解决方案2】:

    一句话。 C 不支持自动创建(隐含)类型和函数参数解构。

    【讨论】:

    • @R.. 足够公平,因为支持 C99 的编译器现在无处不在。
    猜你喜欢
    • 2020-06-28
    • 2011-07-22
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多