返回相同的结构但具有不同的名称

rid*_*rid 0 c c99

struct s1 { int a; int b; };
struct s2 { int a; int b; };

struct s2 test(void) {
    struct s1 s = { 1, 2 };
    return s; // incompatible types
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我可以返回s而不创建一个新struct s2变量并用它s的值填充它吗?保证struct s1始终与之相同struct s2.

nos*_*nos 6

您不能直接返回结构,但可以通过使用复合文字来避免在源代码中创建单独的变量,这是C99的一个功能.

struct s2 test(void) {
  struct s1 s = { 1, 2 };
  return (struct s2){s.a, s.b};
}
Run Code Online (Sandbox Code Playgroud)