复合文字表达式的实际用途?

Practical uses for compound literal expressions?

复合文字的实际应用有哪些?我不太确定未命名存储区域的地址有何用处。

int *pointer = (int[]){2, 4};

我发现这里提到了它们:https://en.cppreference.com/w/c/language/compound_literal

当您无法控制左侧部分时,它们会很有用。如果可能,您可能会使用 int pointer[] = {2, 4};。但是,如果左侧部分由例如定义怎么办?一个外部 API,你想分配给它?复合文字将是一个选项。

复合文字可用于数组,但它们对初始化结构同样有用,允许您将复杂的初始化放在一行中,使代码更易于阅读,编写起来不那么乏味。

像这样:

typedef struct{
  int a,b,c;
  char *d;
}type;

int main(){
  type t=(type){.a=0,.b=1,.c=2,.d="Hello world"};
...

如果没有复合文字,至少需要四行代码。

它们还可以简化变换函数:

typedef struct{
  int a;
  int b;
}twoInts;

twoInts swap(twoInts in){
  return (twoInts){.a=in.b,.b=in.a};
}

这里有一些很棒的:

  • 解决采用指向输入而不是值的指针的接口(可能 return 一个您没有任何理由关心的更新值):

    y = accept(x, &sa, &(socklen_t){sizeof sa});
    
  • 使用命名和 default-zero/null 参数实现函数:

    #define foo(...) foo_func(&(struct foo_args){__VA_LIST__})
    foo(.a=42, .b="hello" /* .c = NULL implicitly */);
    
  • printf 实现自定义格式(自动获取每个宏实例化临时缓冲区):

    #define fmt_mytype(x) fmt_mytype_func((char[MAX_NEEDED]){""}, x)
    printf("...%s...", ..., fmt_mytype(foo), ...);