This is the mail archive of the
mailing list for the GCC project.
Re: Variable length array
- To: L dot Pilo at damtp dot cam dot ac dot uk
- Subject: Re: Variable length array
- From: Craig Burley <burley at gnu dot org>
- Date: Mon, 3 Aug 1998 10:45:33 -0400 (EDT)
- Cc: egcs-bugs at cygnus dot com
- Cc: burley at gnu dot org
>Trying to compile the following with gcc version 188.8.131.52 or egcs-1.0.3
> int dim;
> dim = 3;
> /* GNU variable length array */
> int gnu_array[dim];
> return 0;
>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:
/* GNU variable length array */
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)