首页 > 解决方案 > 在C中返回联合的有效方法?

问题描述

我有一个返回联合的函数,调用者知道如何处理。有没有一种有效的单线方式来返回一个工会?我现在应该做什么:

typedef union { int i; char *s; double d; } FunnyResponse;
FunnyResponse myFunc () {
    // Tedious:
   FunnyResponse resp; 
   resp.d = 12.34;
   return resp;
}
int main () {
   printf ("It's this: %g\n", myFunc().d);
}

这会编译并运行,但是如果可能的话,我希望有一个“返回”行。有任何想法吗?

标签: cunions

解决方案


您可以使用 C99 的指定初始值设定项和复合文字

return (FunnyResponse){ .d = 12.34 };

对于 ANSI C89(Microsoft 的 C 编译器),您必须执行您现在正在执行的操作才能获得相同的效果。


推荐阅读