I was given some code by our professor with some things I have never seen before. I am trying to do my due diligence before I bother (and possibly embarass myself) my professor on the lower level stuff.
First a structure is defined.
struct entry {
char *lexptr;
int token;
};
Then at another point, an array is defined and initialized.
struct entry keywords[] = {
"div", DIV,
"mod", MOD,
0 , 0
};
Where DIV and MOD are #define directives. To my surprise, everything compiles and runs.
Personally, I would have done something novice like..
struct entry keywords[3];
keywords[0]->lexptr="div";
keywords[0]->token=DIV;
//and so on
My first question is, how does that init method work like it does? My best guess is that address location of the array match the order of the elements that were defined in the structure. So the element definintion {"div", DIV,"mod", MOD, 0 , 0}; would nicely fit three elements of entry on the address level.
My second question is, is this normal? Why this way vs my sliglty more readable, yet more verbose, version of initializing the array? Are there any advantages to the first method?
It might be preferable if it was written:
which uses braces around each sub-structure (and there should arguably be a
conston the pointer in the structure definition as well as on the array), but this is how you’d initialize a static array of structures, and it can be used to initialize local arrays too.Also, in C99, you could use designated initializers:
In this example, there is no advantage to the notation (I would not use it), but in more complex cases where, perhaps, only a few of the many fields in a structure need to be initialized in each row, the designated initializers might have an advantage. You can also have initializers out of sequence. Again, you would not use that here, but if you have an
enumfor the entries, you might make use use of[ENUMX] = { ... }, [ENUMY] = { ... }, ...without needing to know the number corresponding to ENUMX and ENUMY. (NB: I could have used the indexing designations without the member designations, or the member designations without the indexing designations; I showed both to illustrate the range of options.)It is much better to use initialization than the executable code that you show as an alternative. The initialization of static or global arrays is done by the system as the program is loaded, so it reduces the execution time, and reduces the volume of code in the executable (both desirable). It also allows the structures to be made constant, so that they can’t be changed at runtime. Assignment requires the structure to be modifiable.