Is it better to use static const vars than #define preprocessor? Or maybe it depends on the context?

What are advantages/disadvantages for each method?

推荐答案

Personally, I loathe the preprocessor, so I'd always go with const.

The main advantage to a #define is that it requires no memory to store in your program, as it is really just replacing some text with a literal value. It also has the advantage that it has no type, so it can be used for any integer value without generating warnings.

Advantages of "const"s are that they can be scoped, and they can be used in situations where a pointer to an object needs to be passed.

I don't know exactly what you are getting at with the "static" part though. If you are declaring globally, I'd put it in an anonymous namespace instead of using static. For example

namespace {
   unsigned const seconds_per_minute = 60;
};

int main (int argc; char *argv[]) {
...
}

C++相关问答推荐

什么C代码将确定打开的套接字正在使用的网络适配器?

Mise()在虚拟内存中做什么?

在32位处理器上优化53—32位模计算>

C语言中字符数组声明中的标准

Malloc(sizeof(char[Length]))是否不正确?

GCC引发不明确的诊断消息

为什么即使在强制转换时,此代码也会溢出?

在C++中使用函数指针的正确语法

CSAPP微型shell 实验室:卡在sigprocmask

加密解密工作正常,但返回错误0x80090005

当b是无符号字符时,int a=(b<;<;2)>;>;2;和int a=b&;0x3F;之间有什么区别?

C语言中的数字指针

如何摆脱-WIMPLICIT-Function-声明

c程序,让用户输入两类数字,并给出输出用户输入多少个数字

如果类型是新的,offsetof是否与typeof一起工作?

UpDown控制与预期相反

使用 GCC 将一个函数中初始化的 struct 体实例通过指针传递到 C 中的另一个函数会产生不同的结果

运行以下 C 程序时出现分段错误

初始化动态分配的布尔二维数组的最佳方法是什么?

使用 SDL2 的 C 程序中的内存泄漏