4

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

George Simms
  • 3,930
  • 4
  • 21
  • 35

2 Answers2

2

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.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
  • It's legal for `register` variables, too. – fuz Jul 11 '15 at 20:24
  • @FUZxxl: `register` implies `auto`. – too honest for this site Jul 11 '15 at 20:36
  • In reality p is dependent on user input, and so I don't think it really makes sense to make it `static` (although as it's in the main function it doesn't make any difference, as you say.) I don't mean "this is constant for all calls to this function" otherwise I might have well declared it outside the function. I just want to pre vent it accidentally being modified subsequently in the function. – George Simms Jul 12 '15 at 14:54
  • @GeorgeSimms: That was more a general addenum. Rmember, there might be other users reading this and wonder why it does not work (although all pieces of the puzzle are given before). – too honest for this site Jul 12 '15 at 15:05
  • @Olaf OK. But I think it is still legitimate, semantically, to have a non-static const – George Simms Jul 13 '15 at 07:52
  • @GeorgeSimms: I did not say (nor imply) the opposite. And I'm perfectly fine with that. – too honest for this site Jul 13 '15 at 12:00
1

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.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94