C - 结构数组初始化中空终止符的含义

C - Meaning of empty terminator in struct array initialization

在检查 PCIe 驱动程序时,我看到了这种类型的结构数组初始化

static struct pci_device_id DWC_ETH_QOS_id[] = {
    { PCI_DEVICE(VENDOR_ID, DEVICE_ID), },
    { },
}

我在设备树 of_device_id 初始化程序中也找到了类似的代码:

static const struct of_device_id rh850_match_table[] = {
    { .compatible = "renesas,rh850" },
    { }
};

为什么末尾有一个空的{}?

感谢您的帮助!

ISO C 语法要求初始化列表为非空,但是,某些编译器(例如 GCC)允许这样做。

这里是关于这个话题的 discussion

如果它为空会发生什么(如果没有 = {...} 部分,你会得到好像为零)的答案是 "yes if the object has static duration, no if not"。

我个人使用我知道的值进行初始化,不依赖于未定义的行为。它可能会限制代码的可移植性,但我怀疑在这种做法很常见的社区中这不是问题(Linux 驱动程序,其中 GCC 是默认编译器。

正如@underscore_d 指出的那样,{} 被添加为标记元素,以便循环遍历这些数组的代码知道何时停止。它依赖于最后一个 'empty' 哨兵元素作为终止条件。

依赖sentinel元素的代码:

结构of_device_idtable: https://elixir.bootlin.com/linux/v4.14.76/source/drivers/of/base.c#L997

结构pci_device_id: https://elixir.bootlin.com/linux/v2.6.35/source/drivers/pci/pci-driver.c#L246