George Simms
George Simms

Reputation: 4060

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.)

Upvotes: 4

Views: 110

Answers (2)

too honest for this site
too honest for this site

Reputation: 12263

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.

Upvotes: 2

Marcus Müller
Marcus Müller

Reputation: 36372

Initializers like these are a C99 feature. I don't know splint, but the splint manual is stuck in the year 2003 -- which means there's a solid probability splint just doesn't speak C99.

Upvotes: 1

Related Questions