在C中的以下陈述中哪一个更好用?
static const int var = 5;
Run Code Online (Sandbox Code Playgroud)
要么
#define var 5
Run Code Online (Sandbox Code Playgroud)
要么
enum { var = 5 };
Run Code Online (Sandbox Code Playgroud) 我目前正在考虑是否更喜欢名称空间枚举或命名空间的静态组的问题.什么应该是默认选择,为什么?
namespace Direction
{
enum Direction
{
north,
east,
south,
west,
};
}
Run Code Online (Sandbox Code Playgroud)
namespace Direction
{
static const unsigned char north = 0;
static const unsigned char east = 1;
static const unsigned char south = 2;
static const unsigned char west = 3;
}
Run Code Online (Sandbox Code Playgroud)
两者都有其优点和缺点.
一些类型的安全:
void foo(Direction dir); // the compiler won't allow you to just pass an int or a value of an unrelated enum without explicitly casting it
Run Code Online (Sandbox Code Playgroud)类型安全性相当有限:
enum A …Run Code Online (Sandbox Code Playgroud)