This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Variable length array


>Trying to compile the following with gcc version 2.7.2.1 or egcs-1.0.3
>
>int main()
>{
>   int dim; 
>   dim = 3;  
>   
>   /* GNU variable length array */
>   int gnu_array[dim]; 
>   return 0;
>} 
>
>I get:
>test.c: In function `main':
>test.c:7: parse error before `int' .
>
>The problem disappear replacing "int dim; dim = 3;" by
>"int dim = 3;"  .

What you're seeing is perfectly normal -- in C, you can't declare
new variables after the first non-declaration executable statement.

Another fix is to move the `int gnu_array[dim];' statement above
the `dim = 3;' statement, though that presumably wouldn't be correct
due to the fact that the automatic array is allocated on procedure
entry.  It is, however, the more typical way automatic arrays are
used -- in procedures taking variables like `dim' as arguments, in
which case they have initial values at the point the automatic
arrays are allocated based on them.

What I don't know offhand is whether gcc promises to execute the
relevant declarations, including automatic arrays, in the order
you specify.  Your fix works, but I notice this doesn't:

  int dim;
  /* GNU variable length array */
  int gnu_array[dim];
  int dum = ++dim;

(I inserted `printf ("size = %d\n", sizeof (gnu_array) / sizeof (int));'
to display the allocated size of the array before returning.)

So you might be able to get away with your workaround in many
straightforward cases, but there might be cases where it doesn't
work due to subtle behaviors.

Make sure you carefully review the gcc documentation and the relevant
C standards, in any case, so you can learn how to avoid not only
the kinds of coding bugs you have, where the compiler complains, but
the worse kind -- the kind where the compiler *doesn't* complain,
but rather generates code that does the wrong thing.

The diagnostic could be more explanative in any case, though.

        tq vm, (burley)


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]