Declaring variables mid-function
llewelly@198.dsl.xmission.com
llewelly@198.dsl.xmission.com
Sat Dec 18 15:52:00 GMT 1999
On Sat, 18 Dec 1999, Shawn wrote:
> I am writing a medium sized program, and ran into a problem where gcc
> would not compile any function that did not have all of its variables
> declared as the first lines of the function. As a test, I wrote this small
> program:
>
ANSI C requires that all variables be declared at the begining of the
block.
> int test(char *tst, char *tst2, char **tst3);
> int test2(void);
>
> int main()
> {
> test2();
>
> char *tst;
> char *tst2;
> char *tst3;
>
> test(tst, tst2, &tst3);
>
> return 1;
>
> }
>
> int test(char *tst, char *tst2, char **tst3)
> {
> return 21;
> }
>
> int test2(void)
> {
> return 21;
> }
>
> When trying to compile this, seemingly simple program, gcc complains. This
> is the output:
>
> bash-2.03$ gcc test.c -o test
> test.c: In function `main':
> test.c:8: parse error before `char'
> test.c:12: `tst' undeclared (first use in this function)
> test.c:12: (Each undeclareed identifier is reported only once
> test.c:12: for each function it appears in.)
> test.c:12: `tst2' undeclared (first use in this function)
> test.c:12: `tst3' undeclared (first use in this function)
This is ANSI conformant behavior; any ANSI C compiler will give you
similar errors.
>
> Does anybody have any idea what is going on here? My system is a Pentium,
> with 48 MB ram, running Slackware Linux 7.0, gcc version 2.91.66 (egcs).
> Thank you in advance!
>
Perhaps you are too acustomed to C++. Unlike C, C++ *does* allow
declaration of variables anywhere in a block. If you wish to code in
C++, compile your code with 'g++', as in: 'g++ test.c -o test'
Your example compiles perfectly with g++; it is correct C++, but not
correct C.
More information about the Gcc-help
mailing list