4

Possible Duplicate:
Variable declaration placement in C

I really dont understand why when I declare variable 'm' like in snipped code below why it doesn't work???I declare m before I use it so what's the point?? thanks

    int main(){

    int a[] = {2,-4,6,47,59,-6,0};
    sort(a, 7);

    int m;
    for(m = 0; m < 7; m++){
        printf("%d ",a[m]);
    }
}

But if I put declaration at beggining, above the array, it works.

Community
  • 1
  • 1
exeq
  • 379
  • 1
  • 5
  • 15

4 Answers4

5

Looks like you are compiling in ANSI C mode. In C89, variable declaration is allowed only at the beginning of a block.

Since C99, this restriction has been removed. Compile with -std=c99 which will allow you to declare variables anywhere.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • I use compiler within Visual Studio 2010, I begin C++ project and in properties change to Compile as C code (/TC) What does it mean?? – exeq Oct 27 '12 at 20:12
  • Visual Studio supports only few C99 features. So you may have to declare variables at the beginning of a block. Simply move `int m;` to the top of main().For more information: [Visual Studio support for new C / C++ standards?](http://stackoverflow.com/questions/146381/visual-studio-support-for-new-c-c-standards). – P.P Oct 27 '12 at 20:16
2

as far as i know in C, all declarations must be above the code

Abdusalam Ben Haj
  • 5,343
  • 5
  • 31
  • 45
1

You're probably using a compiler that supports C99 partially(or doesn't support it at all), in which, in-place variable declaration is forbidden.

Using such a compiler would need you to declare your variables before an "executable" code.

This was a restriction in C89 and previous.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
0

Not actually an answer but I can't comment on questions yet. I agree with people's answer above regarding the C implementation you;re using is causing the error. What I suggest you try is for (int m = 0, ...) for two reasons: to see if it compiles, and scope (from the looks of it you don't need m outside the for loop) Hope this helps

Carlos
  • 208
  • 1
  • 6