简体   繁体   中英

C90 compound literals

In C99, if x was declared earlier and is of type v2 , then I can write:

x = (v2) { 1, 2 };

where v2 is:

typedef struct {
    int x;
    int y;
} v2;

Can I do something similar in C90?

AFAIK, compound literals were introduced exactly in C99. However, if you're using GCC, this feature is available as an extension. Quoting GCC docs :

ISO C99 supports compound literals. A compound literal looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer; it is an lvalue. As an extension, GCC supports compound literals in C90 mode and in C++ .

Another note regarding this feature of GCC:

As a GNU extension, GCC allows initialization of objects with static storage duration by compound literals (which is not possible in ISO C99, because the initializer is not a constant). It is handled as if the object was initialized only with the bracket enclosed list if the types of the compound literal and the object match. The initializer list of the compound literal must be constant. If the object being initialized has array type of unknown size, the size is determined by compound literal size.

 static struct foo x = (struct foo) {1, 'a', 'b'}; static int y[] = (int []) {1, 2, 3}; static int z[] = (int [3]) {1}; 

The above lines are equivalent to the following:

 static struct foo x = {1, 'a', 'b'}; static int y[] = {1, 2, 3}; static int z[] = {1, 0, 0}; 

The closest you can get in C90 without compiler extensions would be:

{
    v2 temp = { 1, 2 };
    x = temp;
}

which you could compress to one line or replace with a macro. (Since C does not have hygienic macros, however, you have to be careful with macros that declare variables, of course.)

No, this is a C99 feature. However, some compilers will allow it as an extension in C89 mode, eg gcc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM