Is it possible to partially initialize a struct?

Hi, my question is to ask whether or not it is possible to partially initialize a struct in C language with Keil C166 compiler.

According to C syntax [1], it should be possible to do things like:

struct {
    int a;
    int b;
    int c;
} S = {
    .b = 0,
    .c = 1,
};

In the example above, only the selected members of the structure are given default values, the others are not.

However, the C166 compiler seems not to understand this expression. When compiling, it reports error: MAIN.C(14): error C25: syntax error near '.'

The reason why i am asking this question is because: the Keil compiler by default creates sections ?C_INITSEC and ?C_CLRMEMSEC which store data for START_V2.A66 to clear variables to zero and assign initialized values at CPU start up. So it will save (well, only a little bit) memory in the ?C_INITSEC by inilizing only non-zero varialbes or struct members only.

[1] en.wikipedia.org/.../C_syntax

Parents
  • In the example above, only the selected members of the structure are given default values, the others are not.

    Setting aside the issue of C99 vs. C90, I'm afraid you've misunderstood what this actually does.

    No, there is no way, even in C99, to initialize only parts of a struct. A struct is always completely initialized, or completely uninitialized. Just because an element is not given an explicit initializer doesn't mean it won't be initialized --- it only means that the initial value is zero.

    The situation is not significantly different from "missing" initializer elements at the end of a traditional C90 struct definition:

    struct foo {int a; int b; int c;} foo = {3};
    

    'b' and 'c' are initialized to zero by default. And yes, those zeroes will end up in the master copy of initialized data in the program image. To avoid that, parts of the struct would have to be located in different memory locations. That's clearly impossible.

Reply
  • In the example above, only the selected members of the structure are given default values, the others are not.

    Setting aside the issue of C99 vs. C90, I'm afraid you've misunderstood what this actually does.

    No, there is no way, even in C99, to initialize only parts of a struct. A struct is always completely initialized, or completely uninitialized. Just because an element is not given an explicit initializer doesn't mean it won't be initialized --- it only means that the initial value is zero.

    The situation is not significantly different from "missing" initializer elements at the end of a traditional C90 struct definition:

    struct foo {int a; int b; int c;} foo = {3};
    

    'b' and 'c' are initialized to zero by default. And yes, those zeroes will end up in the master copy of initialized data in the program image. To avoid that, parts of the struct would have to be located in different memory locations. That's clearly impossible.

Children
More questions in this forum