Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell Visual Studio/Microsoft's C compiler to allow variable declarations after the first statement?

I have code that compiles on the GNUARM compiler, but Visual Studio 2010 issues errors. The issue involves declaring variables after the first statement in a C language file:

main.c

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

int main(void)
{
  int i = 6;
  i = i + 1;
  printf("Value of i is: %d\n", i);
  int j = i * 10; // <-- This is what Visual Studio 2010 complains about.
  printf("Value of j is: %d\n", j);
  return EXIT_SUCCESS;
}

The following code compiles without errors:

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

int main(void)
{
  int i = 6;
  int j;      // <-- Declaration is now here, valid according to K&R rules.
  i = i + 1;
  printf("Value of i is: %d\n", i);
  j = i * 10; // <-- Moved declaration of j to above.
  printf("Value of j is: %d\n", j);
  return EXIT_SUCCESS;
}

I'm using default settings for creating a Win32 console project. When I set "Compile as" property to "Compile as C++ (/TP)", I get compilation errors in some Visual Studio header files. (Right click on project, choose PropertiesConfiguration PropertiesC/C++Advanced).

How do I tell Visual Studio 2010 to allow variable declarations after the first statement, like C++ or the current C language standard?

like image 421
Thomas Matthews Avatar asked Sep 30 '11 18:09

Thomas Matthews


2 Answers

You don't. Visual C++ does not support C99.

You'll need to compile as C++ (and update your code accordingly) or follow the rules of C89.

(I don't know what errors you get when compiling with /TP; I can compile your example successfully with /TP if I add #include <stdlib.h> for EXIT_SUCCESS; if you provide more details, I or someone else may be able to help.)

like image 167
James McNellis Avatar answered Oct 24 '22 11:10

James McNellis


As of Visual Studio 2013, the Visual C++ compiler supports C99 style variable declarations. More details can be found in:

http://blogs.msdn.com/b/vcblog/archive/2013/06/28/c-11-14-stl-features-fixes-and-breaking-changes-in-vs-2013.aspx

like image 39
HYildiz Avatar answered Oct 24 '22 09:10

HYildiz