复合文字的实际应用是什么?我不太确定未命名的存储区域的地址如何有用。
int *pointer = (int[]){2, 4};
我发现他们在这里提到:https ://en.cppreference.com/w/c/language/compound_literal
复合文字的实际应用是什么?我不太确定未命名的存储区域的地址如何有用。
int *pointer = (int[]){2, 4};
我发现他们在这里提到:https ://en.cppreference.com/w/c/language/compound_literal
这里有一些很棒的:
处理采用指向输入而不是值的指针的接口(可能返回您没有任何理由关心的更新值):
y = accept(x, &sa, &(socklen_t){sizeof sa});
使用命名和默认零/空参数实现函数:
#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), ...);
复合文字可用于数组,但它们对于初始化结构同样有用,允许您将复杂的初始化放在一行中,从而使代码更易于阅读,并且编写起来不那么乏味。
像这样:
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};
}
当您无法控制左侧部分时,它们会很有用。如果可能,您可能会使用int pointer[] = {2, 4};
. 但是,如果左侧部分是由外部 API 定义的,而您想分配给它呢?复合文字将是一种选择。