问题描述
哪个更好用C下面的语句中使用?
静态const int的无功= 5;
或
的#define VAR 5
或
枚举{VAR = 5};
一般来说:
静态常量
由于它尊重范围和类型是安全的。
唯一的告诫我可以看到:如果你想在命令行上可能定义的变量。还有一种替代方案:
#IFDEF VAR //非常不好的名字,不够长,过于笼统,等等。
静态INT常量VAR = VAR;
#其他
静态INT常量VAR = 5; // 默认值
#万一
只要有可能,而不是宏/省略号,使用类型安全的替代品。
如果你真的需要去一个宏(例如,你希望 __ FILE __
或 __ LINE __
),然后你最好命名您的宏非常小心:在其的建议全部大写,由项目(这里BOOST_)的名称开始,在应聘一个库,你会发现这是(一般)的特定区域(库),然后用一个有意义的名称的名称
这通常使得冗长的名字:)
Which one is better to use among the below statements in C?
static const int var = 5;
or
#define var 5
or
enum { var = 5 };
Generally speaking:
static const
Because it respects scope and is type-safe.
The only caveat I could see: if you want the variable to be possibly defined on the command line. There is still an alternative:
#ifdef VAR // Very bad name, not long enough, too general, etc..
static int const var = VAR;
#else
static int const var = 5; // default value
#endif
Whenever possible, instead of macros / ellipsis, use a type-safe alternative.
If you really NEED to go with a macro (for example, you want __FILE__
or __LINE__
), then you'd better name your macro VERY carefully: in its naming convention Boost recommends all upper-case, beginning by the name of the project (here BOOST_), while perusing the library you will notice this is (generally) followed by the name of the particular area (library) then with a meaningful name.
It generally makes for lengthy names :)
这篇关于"静态常量" VS"#定义" VS"枚举"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!