静态常量与#define

static const vs #define(静态常量与#define)
本文介绍了静态常量与#define的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 static const 变量比使用 #define 预处理器更好吗?或者这取决于上下文?

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?

推荐答案

就个人而言,我讨厌预处理器,所以我总是使用 const.

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

#define 的主要优点是它不需要内存来存储您的程序,因为它实际上只是用文字值替换一些文本.它还有一个优点是它没有类型,所以它可以用于任何整数值而不会产生警告.

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.

const"的优点是可以限定范围,可以在需要传递对象指针的情况下使用.

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.

不过,我不知道您对static"部分的确切含义.如果您是全局声明,我会将它放在匿名命名空间中,而不是使用 static.例如

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[]) {
...
}

这篇关于静态常量与#define的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)