了解 C 中的静态变量声明/初始化 [英] Understanding static variables declaration/initialization in C

查看:47
本文介绍了了解 C 中的静态变量声明/初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have only one file in my project called test.c; the code below does not compile if I do not define "TRUE". I use vc. I just want to understand the behavior. Please throw some light on this aspect.

#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; 
}

推荐答案

那是因为定义了变量之后就不能再声明了.但是,您可以在声明后定义一个变量.

That is because you can not declare a variable after you have defined it. However you may define a variable after you declare it.

#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 

这篇关于了解 C 中的静态变量声明/初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆