Weird compilation error in Visual Studio 2008

2019-01-26 18:56发布

I have a problem compiling the following code:

#include <stdio.h>
#include <limits.h>
int main () {
    printf("short: [%d,%d]\n",SHRT_MIN,SHRT_MAX);
    printf("int: [%d, %d]\n",INT_MIN, INT_MAX);
    printf("long: [%d, %d]\n",LONG_MIN,LONG_MAX);
    int aa=017;
    printf("%d\n",aa);
    return 0;
}

Error message is:

1>c:\tic\ex1\ex2\ex2.c(12) : error C2143: syntax error : missing ';' before 'type'
1>c:\tic\ex1\ex2\ex2.c(13) : error C2065: 'aa' : undeclared identifier

However, compilation for this is fine:

    #include <stdio.h>
    #include <limits.h>
    int main () {
        int aa=017;
        printf("short: [%d,%d]\n",SHRT_MIN,SHRT_MAX);
        printf("int: [%d, %d]\n",INT_MIN, INT_MAX);
        printf("long: [%d, %d]\n",LONG_MIN,LONG_MAX);
        printf("%d\n",aa);
        return 0;
    }

Any idea what the issue is?

7条回答
爷的心禁止访问
2楼-- · 2019-01-26 19:17

change the file type to cpp then it will work (and you can add c++ to your resume)

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-26 19:23

In (old) C, you cannot declare a variable anywhere as you can in C++ or in the latest C standards. You have to declare it directly after the open curly brace of a scope, as in your second example.

查看更多
Anthone
4楼-- · 2019-01-26 19:26

In C, variables previously had to be declared at the top of the scope, before any code is executed. This isn't the case in C99 (which Visual Studio doesn't implement.)

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-26 19:29

In C prior to C99, all variables in a given scope have to be defined before other statements in that scope. Though it initially looks the same, this isn't quite the same as GMan's answer. In particular, a function can contain other blocks that define other scopes, and those can define variables after executable statements in the outer block:

int main() { 
    int x;

    printf("whatever");
    int y; // not allowed

    { 
         int z;    // allowed
    }
    return 0;
}

While defining a block like this (that's not associated with any flow control like an if statement or while loop) is fairly uncommon, it is allowed as a part of C.

查看更多
姐就是有狂的资本
6楼-- · 2019-01-26 19:35

Unless you explicitly tell it to compile as C, doesn;t visual studio compile .c files as c++ anyway? You can certainly use // commnets

查看更多
虎瘦雄心在
7楼-- · 2019-01-26 19:39

In "classic" C language (C89/90) declarations are not allowed to appear in the middle of the code. Your original declaration of aa would be valid in C++ or in the "new" C (C99), but not in C89/90.

VS 2008 comes with the C89/90 compiler, which is why you get these errors.

On top of that, the proper printf format specifier for priting long values is %ld, not %d.

查看更多
登录 后发表回答