1

I have a great experience of C++, and now I'm trying to do some things in pure C. But I noticed a really strange fact.

The following code:

#include <stdio.h>

int main()
{
    double a;
    scanf_s("%lf", &a);

    double b;
    b = a + 1;

    printf("%lf", b);

    return 0;
}

compiles OK in sourceLair (with gcc compiler, as well as I know), but generates following errors in Microsoft Visual Studio (with Visual C++):

1>Task 1.c(8): error C2143: syntax error : missing ';' before 'type'
1>Task 1.c(9): error C2065: b: undeclared identifier
1>Task 1.c(9): warning C4244: =: conversion from 'double' to 'int', possible loss of data
1>Task 1.c(11): error C2065: b: undeclared identifier

I experimented a bit with the code and noticed that placing a variable declaration before calling any function is OK, but placing a declaration after it results in compilation error.

So what's wrong? I use a fresh installation of Microsoft Visual Studio 2012 Express with no settings changed.

Ivan Akulov
  • 4,323
  • 5
  • 37
  • 64

1 Answers1

4

Assuming that this is being compiled as C, I have bad news for you: Microsoft's compiler that comes with Visual Studio does not support C99, only C89, and in that revision of the language, one can only declare variables at the beginning of a scope. A declaration after a non-declaration statement is an error.

So, either rewrite your code so that it conforms to C89, or use a compiler that supports C99 (such as GCC, that can be used after installing MinGW, or clang, which only has experimental support for integration with VS).

  • 2
    also note that clang has experimental Visual Studio integration - you can get binary builds from http://llvm.org/builds/ ; other alternatives would be [Pelles C](http://www.smorgasbordet.com/pellesc/) with its own IDE or the Intel compiler, which I believe comes with Visual Studio integration as well – Christoph Sep 27 '13 at 19:04
  • @Christoph I didn't know that, thanks. I've now included it in my answer. –  Sep 27 '13 at 19:05