Recently, when I looked at Linux code, we found a new initialization method for struct struct, which was summarized as follows:
1. Sequence initialization
In textbooks, C language structure initialization is in the order of the way, there is no way to deal with the chaotic sequence. The sequential initialization of the struct must be in accordance with the order of the members, indispensable, if the structure is larger, prone to errors, and the form is not intuitive, you can not see the values of each struct data member.
2. Random sequence Initialization
Chaotic initialization is a new addition to the C99 standard, a more intuitive way to initialize. In the case of sequential initialization, the sequence initialization is like its name, the members can be initialized in order, and only some members can be initialized, and the extensibility is better. The Linux kernel initializes the struct in this way.
There are currently 3 different ways to initialize a sequence of chaos:
One is to use the dot (.) symbol, the second is with a colon (:), and the third is to use the index initialization when the field is an array.
The more recommended way is the first!
Look directly at the sample code:
1typedefstructAl_data2 {3 intA;4 intb;5 intC;6 Charch;7 }al_data;8 9 structAl_data AD =Ten { One 1, A 3, - 9, - 'A', the }; - - structAl_data ad2 = - { +. A =2, -. B =6, +. C = -, A. ch ='B', at }; - - structAl_data ad3 = - { -A:3, -B:9, inC: -, -Ch:'C' to }; + - the intMain () * { $ Panax Notoginsengprintf"ad.a=%d, ad.b=%d, ad.c=%d, ad.ch=%c \ n", AD.A, ad.b, AD.C, ad.ch); -printf"ad2.a=%d, ad2.b=%d, ad2.c=%d, ad2.ch=%c \ n", ad2.a, ad2.b, ad2.c, ad2.ch); theprintf"ad3.a=%d, ad3.b=%d, ad3.c=%d, ad3.ch=%c \ n", ad3.a, ad3.b, ad3.c, ad3.ch); + return 0; A}
The above is the sequence initialization and the first two kinds of chaos initialization.
It is true that the results can be initialized successfully.
Finally, we look at the array index initialization method:
1 structSt_al2 {3 inti;4Al_data ald[3];5 };6 7 structSt_al SA =8 {9. i =1,Ten. ALD = One { A[0] = {4,5,6,'Q'}, -[1] = {8,9,Ten,'W'}, - }, the};
The verification is also passed! But in fact the index after the content is also the shape of the order initialization ....
Finally write a trap, do not mix different initialization methods, so as not to bring unexpected errors
For example: use first. Initialization followed by sequential initialization is the next element value of the previous element, which is prone to error
1 struct al_data ad2 =2{3 ,4 6 , 5 3 , 6 ' B ' , 7 };
Line 5th is actually equivalent to. C = 3
No initialization of a assignment for 0, but not absolute, requires 0 or manual assignment!
Three forms of Linux C struct initialization