1

I'm struggling to understand why I get an error in the following code when trying to compile:

#include <stdlib.h>
#include <stdio.h>

int main()
{
    puts("");
    int i = 0;

    return 0;
}

If I comment out the puts("");, it will compile.

I'm using Visual Studio, and I complie this as C Code, using /TC.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
RayOldProf
  • 990
  • 2
  • 13
  • 40

2 Answers2

8

Visual Studio C is somewhat dated and uses C89.

For C89, you must declare all of your variables at the beginning of a scope block.

In the case of your code above, this should work

int main()
{
    int i = 0;
    puts("");
    return 0;
}

Note that you could also do the following

int main()
{
    puts("");
    {
        int i = 0;
    }
    return 0;
}
Community
  • 1
  • 1
Gearoid Murphy
  • 11,387
  • 17
  • 65
  • 86
  • 1
    Important note on the second example: `i` is only valid within `{}`. Secondly MSVS does mostly "use" C89, however that's not entirely true. It does support some of the C99 features, however `statement before declaration` isn't one of them. – Jite Sep 18 '13 at 11:21
  • Thx for the quick response and a great answer. Out of curiosity; do you know if it is possible to change the compiler in the visual studio? – RayOldProf Sep 18 '13 at 11:28
  • @RezaAyadipanah, yes, you can do a "Makefile project" and set up the compiler within the makefile to be whatever you want. – Vicky Sep 18 '13 at 11:33
1

I think you are using older C standard C89.

C89 standard doesn't allow to declare variables after some function call. All the variable declaration should be at the start of the scope block (Thanks, Gearoid Murphy).

Don't You Worry Child
  • 5,896
  • 2
  • 24
  • 50