3

我的项目中只有一个名为 test.c 的文件;如果我没有定义“TRUE”,下面的代码将无法编译。我用vc。我只是想了解这种行为。请对这方面有所了解。

#ifdef TRUE
static int a; 
static int a = 1; 
#else 
static int a = 1; 
static int a; 
#endif 

int main (void) 
{ 
    printf("%d\n", a);
    return 0; 
}
-----------------------
#ifdef TRUE     // both ok
int a; 
int a = 1; 
#else           // both ok
int a = 1; 
int a; 
#endif

int main (void) 
{ 
    printf("%d\n", a);
    return 0; 
}
4

2 回答 2

8

那是因为你不能在定义变量后声明它。但是,您可以在声明变量后定义它。

#ifdef TRUE
static int a; //Declaring variable a
static int a = 1; //define variable a
#else 
static int a = 1; //define variable a
static int a; //Error! a is already defined so you can not declare it
#endif 
于 2011-12-07T15:09:10.163 回答
-3

显然,编译器不允许您重新定义已初始化的变量。

于 2011-12-07T15:07:26.743 回答