static const vs #define [英] static const vs #define

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

问题描述

是否最好使用 static const vars比 #define 预处理器?或者也许取决于上下文?



每个方法的优点/缺点是什么?

解决方案



一个#define的主要优点是它不需要预处理器,内存存储在你的程序中,因为它真的只是用一个文本值替换一些文本。它还具有没有类型的优点,因此它可以用于任何整数值,而不产生警告。



const的优点是它们可以scoped,并且它们可以用于需要传递对象的指针的情况。



我不知道你正在使用的是static 部分。如果你在全局声明,我会把它放在一个anonomous命名空间,而不是使用静态。例如

 命名空间{
unsigned const seconds_per_minute = 60;
};

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


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 anonomous namespace instead of using static. For example

namespace {
   unsigned const seconds_per_minute = 60;
};

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

这篇关于static const vs #define的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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