您的位置:首页 > 编程语言 > C语言/C++

关于c 和 c++ 中定义全局常量的异同

2016-07-19 15:39 387 查看
之前学习c语言的时候,要用到全局的常量,必须要在.h文件中用static const 定义。

例如:

global.h

#include <stdio.h>
static const int a = 5;
static const float b = 5;
extern int c;
void test();

test.c
#include "global.h"
int c = 7;
void test() {
printf("a = %d\n", a);
printf("b = %f\n", b);
c = 6;
}
main.c#include "global.h"
int main() {
test();
printf("a = %d\n", a);
printf("b = %f\n", b);
printf("c = %d\n", c);
return 0;
}

然后,转到c++以后,自然而然的保留了这个习惯。直到今天,在一个项目中发现全局常量居然没用static修饰,链接时也没问题,才直到,在c++中,是不用static 修饰全局常量也没问题的。只是,全局的常量,一定要用const限定。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: