首页 > 解决方案 > 在一行上初始化并返回结构

问题描述

是否可以在 C 中的一行上初始化并返回一个结构?

typedef struct {
    long tau;
    float probability;
} pitch_result;

pitch_result f(){
    pitch_result result = {0, 0};
    return result;
}

标签: c

解决方案


好吧,你可以像这样返回一个复合文字

return (pitch_result) {0, 0};

这也可以与赋值一起使用,不应与初始化混淆。

这不起作用:

pitch_result x;
x = {0, 0};

但这会

pitch_result x;
x = (pitch_result) {0, 0};

复合文字看起来像演员表,但事实并非如此。例如,它是一个左值。这确实编译(但我看不出它有什么用处):

(pitch_result){0, 0} = (pitch_result) {1, 1};

推荐阅读