views:

559

answers:

5

Hey guys,

The trouble here is that i cant declare variables inside a function after the function already has some statements in it. Declaring at the start works fine, but after something, it gives a parse error. for example:

int main()
{
 int b;
 b = sisesta();
 float st[b];

 return 0;
}

Id like to declare an array st with its size being returned by another function, but it wont let me do it! Says "Parse error before float". This is in C by the way, but I guess its identical to what it would be in other languages with the same syntax.

Any help appreciated.

+3  A: 

Dude in C you have to declare all variables at the start. You can't declare between statements

Raghu
You mean "At the start of the scope".
OJ
At the start of the block, for C prior to ISO/IEC 9899:1999 (C99)
Chris Young
+5  A: 

In C standards before C99, you have to declare your local variables at the beginning of the function. Beginning with C99, this is no longer required.

Since Dev-C++ ships with gcc and recent gcc versions do support C99 partially, you can try adding -std=c99 to the gcc argument list in the Dev-C++ settings to trigger C99 mode.

DrJokepu
A: 

you could malloc() a float* to the size you want (just remember to free() it afterwards):

int main()
{
 int b;
 float *st;

 b = sisesta();

 if((st = malloc(sizeof float * b)) == NULL){exit 1;}

 /* blah blah */

 free(st);
 return 0;
}
dsm
Why the downvote? It is a perfectly fine solution to the problem.
DrJokepu
A: 

It turns out that I just had an old version of DevC++ which didnt support the newer standard, with the latest release the statements work fine, thanks for the help anyway.

A: 

Even in C89, it was just a stylistic choice to do all declarations at the beginning of a function - the trouble that you hit in your code was that you attempted to declare an array on the stack of an unknown size, and that was not allowed until C99. If you were to do the same code, but replace "float st[b]" with a statement where "b" was constant, it would work, like "float st[10]"