Can't declare variables after statements in DevC ++

The problem is that I cannot declare variables inside a function after the function already contains some operators. The declaration at the start is fine, but after something it gives a parse error. For example:

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

 return 0;
}

      

I would like to declare an array st

with its size returned by another function, but that won't let me do that! Says "Analysis error before float". It's in C by the way, but I think it is identical to what it would be in other languages ​​with the same syntax.

Any help was appreciated.

+1


source to share


5 answers


In the C pre-C99 standards, you must declare your local variables at the beginning of the function. As of C99, this is no longer required.



Since Dev-C ++ ships with gcc and recent versions of gcc partially support C99, you can try adding -std=c99

gcc to the argument list in Dev-C ++ settings to get C99 mode running.

+6


source


Dude in C you need to declare all the variables at the beginning. You cannot declare between operators



+2


source


you can malloc()

a float*

size you want (just remember free()

after that):

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

 b = sisesta();

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

 /* blah blah */

 free(st);
 return 0;
}

      

0


source


It turns out I just had an old version of DevC ++ that didn't support the new standard, with the latest version the operators work fine, thanks for the help anyway.

0


source


Even in C89, it was just a stylistic choice to make all the declarations at the start of a function - the problem you got into the code was that you were trying to declare an array on a stack of unknown size, and which is not allowed until C99. If you did the same code but replace "float st [b]" with a statement where "b" was constant, it would work like "float st [10]"

0


source







All Articles