定义

1.C99标准引入的新特性,它允许我们在不定义变量的情况下,直接使用字面量来初始化一个对象。复合字面量的语法形式为:(type){initializer}

2.type是一个类型名,initializer是一个初始化器,它可以是一个常量、一个表达式或者一个初始化列表。复合字面量可以用于数组、结构体、联合体等类型的初始化。

3.例如,(int[\]){1, 2, 3}表示一个匿名的整型数组,它的元素分别为1、2、3。(struct point){.x=1, .y=2}表示一个匿名的结构体变量,它有两个成员变量x和y,分别被初始化为1和2。

约束条件
  • The type name shall specify an object type or an array of unknown size, but not a variable length array type.
    type name指定了数组类型或结构体类型,数组长度不能是可变的。
  • No initializer shall attempt to provide a value for an object not contained within the entire unnamed object specified by the compound literal.
    匿名"对象"的初始化必须在在复合字面量的大括号中。
  • If the compound literal occurs outside the body of a function, the initializer list shall consist of constant expressions.
    如果复合字面量是文件作用域,initializer list的表达式必须是常量表达式。
参考例子
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MKTAG(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((unsigned)(d) << 24))

#define AV_FOURCC_MAX_STRING_SIZE 32
#define av_fourcc2str(fourcc) av_fourcc_make_string((char[AV_FOURCC_MAX_STRING_SIZE]){0}, fourcc)

char *av_fourcc_make_string(char *buf, uint32_t fourcc)
{
int i;
char *orig_buf = buf;
size_t buf_size = AV_FOURCC_MAX_STRING_SIZE;

for (i = 0; i < 4; i++) {
const int c = fourcc & 0xff;
const int print_chr = (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c && strchr(". -_", c));
const int len = snprintf(buf, buf_size, print_chr ? "%c" : "[%d]", c);
if (len < 0)
break;
buf += len;
buf_size = buf_size > len ? buf_size - len : 0;
fourcc >>= 8;
}

return orig_buf;
}

int main(int argc, char** argv)
{
uint32_t type = MKTAG('r', 'o', 'o', 't');
printf("%s\n", av_fourcc2str(type));
return 0;
}