ILD

Compound literals
作者:Yuan Jianpeng 邮箱:yuanjp89@163.com
发布时间:2020-2-10 站点:Inside Linux Development

可以认为等价于匿名数组或者匿名结构体变量。


来看它的一个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
    struct proto **proto = (struct proto* []) {
        & ctx->lan, 
        & ctx->wan,
        0,  
    };  
 
    while (*proto) {
        if (setup_proto(*proto) < 0) {
            plog(NETMAN, ERR, "setup proto %s failed", (*proto)->name);
            return -1;                                                                                                                                                                                                           
        }   
        proto++;
    }

某些情况下,可以使编码更简洁 。


结构体的例子:


Usually, the specified type is a structure.  Assume thatstruct foo and structure are declared as shown:

     struct foo {int a; char b[2];} structure;

Here is an example of constructing a struct foo with a compound literal:

     structure = ((struct foo) {x + y, 'a', 0});

This is equivalent to writing the following:

     {
       struct foo temp = {x + y, 'a', 0};
       structure = temp;
     }


In C, a compound literal designates an unnamed object with static or automatic storage duration.


参考:

https://gcc.gnu.org/onlinedocs/gcc-4.8.0/gcc/Compound-Literals.html


Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.