Search code examples
cinitializationsplint

Is it legal to use a variable in a struct initializer in C?


The following code seems to compile fine.

typedef struct Test {
  int i;
  int j;
} Test;

int main() {
  int i;
  i = 0;
  Test p = {i, 1};
  printf("%d\n", p.i);
  return 0;
}

Splint fails with

example2.c:9:7: Parse Error. (For help on parse errors, see splint -help
           parseerrors.

(This is the line Test p = {i, 1};)

Is this illegal C, or is this a bug in splint?

(I want to do this because I want p to be const, although the failure seems to happen even when I remove the const modifier. If I move the declaration and initialization of i onto one line, the problem also seems to go away.)


Solution

  • It is legal since C99 as that is an automatic variable. It is not legal, however, for global and static variables. gcc also allows this for pre-C99 as an extension (still auto only, of course).

    I generally recommend to use at least C99-compatible compilers, as there are some subtle differences to the earlier standard and C99 introduces many useful features, like C++ line-comments, _Bool, etc.

    Note: p is initialized at run-time and each time the function is called (main is normally called only once, but the rule also applies here). No matter if you make it const or not. In general, for const variables (sic!), it is better to also have them static or global to save the run-time overhead. OTOH, this (see above) disallows a variable initializer.