Ardo
Ardo

Reputation:

Can't declare variables after statements in DevC++

The trouble here is that I can't 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;
}

I'd like to declare an array st with its size being returned by another function, but it won't 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.

Upvotes: 1

Views: 1866

Answers (5)

Adam
Adam

Reputation:

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]"

Upvotes: 0

Ardo
Ardo

Reputation:

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.

Upvotes: 0

dsm
dsm

Reputation: 10395

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;
}

Upvotes: 0

Tamas Czinege
Tamas Czinege

Reputation: 121394

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.

Upvotes: 6

Raghu
Raghu

Reputation: 190

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

Upvotes: 2

Related Questions