Initializing structures in C
I have been using C for over 30 years; using it, teaching it, writing about it, supporting users. Of course, over that time the language has developed and a selection of new standards have emerged. I was always attracted by the simplicity of C – there always seemed to be just enough language to get the job done, with a bit of flexibility for style. In some ways, I preferred a precursor of C, BCPL, but that is another story. As new features have been added to the language, I have worried that C will become increasingly bloated and its original appeal will be lost. I have generally reviewed the new features and ignored those that are inapplicable or unwise for embedded use. It was a surprise when I stumbled across a feature which looks neat and useful, that must have been sneaked in at some point …
It is clearly very good programming practice to initialize a variable before use and this is probably best done when the variable is declared. Fortunately, C gives us some simple syntax to achieve this. So, we can write:
int i = 99; // loop counter
This is quite clear, but, in an embedded context, we might like to ponder exactly how this initialization takes place. With a desktop computer, the program image is read from disk into memory, with variables containing their initial values. Many embedded systems copy an image from flash to RAM on start up, so the same approach can apply. However, sometimes code is executed out of some read-only memory. Under these circumstances, some code must be included so that, on start up, data is copied into the initialized variables.
C allows us to initialize more complex objects, like arrays:
int a[3] = {10, 20, 30};
and structures:
struct s { int s1; int s2; int s3; };
struct s m = {1, 2, 3};
It is also possible to initialize just the initial elements of an array, leaving the remainder uninitialized [and probably 0]:
int a[3] = {10, 20};
Whilst I cam imagine situations where doing this with an array might make sense, it would be hard to imagine that being able to do the same with an array would make sense, but you are allowed to do it:
struct s m = {1, 2};
There is no mechanism for initializing arbitrary array members, only the initial ones. However [and this is the feature of which I was previously unaware], you can do this with structures:
struct s n = {.s2 = 4};
Although this adds little benefit in this trivially simple example, it would make for quite readable code with a large, complex structure.
BTW, it seems that this feature is not available in C++ …
Comments