关于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限定。
例如:
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限定。
相关文章推荐
- 计数排序
- 分析C语言一个简单程序
- windowsViaC/C++设备IO之异步设备IO请求
- C++ 语法 :#pragma once 与 #ifndef ...#define ...#endif
- C++异常处理机制详解
- windowsViaC/C++设备IO之同步的设备I/O
- 设计模式之观察者模式(C++)
- QT学习之路————C语言操作sqlite数据库
- C++ vector 实现
- C++類庫文件使用(不用.h文件)
- 【uoj218】火车管理 题解&代码(C++)
- C++的开源库--boost
- C++语法 :C++中的头文件和源文件
- 242. Valid Anagram
- windowsViaC/C++之设备I/O之文件设备
- C语言KMP字符串匹配算法
- c++面试关键字整理
- 171. Excel Sheet Column Number
- POJ3169 差分约束系统 解题报告
- 168. Excel Sheet Column Title