在C语言中,下列语句中使用哪个更好?

static const int var = 5;

or

#define var 5

or

enum { var = 5 };

当前回答

使用const而不是#define总是更好。这是因为const是由编译器处理的,而#define是由预处理器处理的。这就像#define本身不是代码的一部分(粗略地说)。

例子:

#define PI 3.1416

符号名称PI可能永远不会被编译器看到;它可能在源代码到达编译器之前被预处理器删除。因此,名称PI可能无法进入符号表。如果在编译过程中遇到涉及使用常量的错误,这可能会令人困惑,因为错误消息可能指向3.1416,而不是PI。如果圆周率定义在一个你没有写的头文件中,你就不知道3.1416是从哪里来的。

这个问题也可能在符号调试器中突然出现,因为您正在编程的名称可能不在符号表中。

解决方案:

const double PI = 3.1416; //or static const...

其他回答

我们查看了MBF16X上生成的汇编代码…这两种变体产生相同的算术运算代码(例如ADD Immediate)。

所以const int是类型检查的首选,而#define是旧风格。也许它是特定于编译器的。因此,请检查生成的汇编程序代码。

静态const和#define之间的区别在于前者使用内存,而后者不使用内存进行存储。其次,您不能传递#define对象的地址,而可以传递静态const对象的地址。实际上,这取决于我们所处的环境,我们需要在这两者中选择一个。两者在不同的情况下都处于最佳状态。请不要认为一个比另一个好。: -)

如果是这样的话,丹尼斯·里奇会把最好的留下来……哈哈哈……: -)

在c#中定义更为流行。你可以使用这些值来声明数组大小,例如:

#define MAXLEN 5

void foo(void) {
   int bar[MAXLEN];
}

据我所知,ANSI C不允许你在这种情况下使用静态常量。在c++中,在这些情况下应该避免使用宏。你可以写

const int maxlen = 5;

void foo() {
   int bar[maxlen];
}

甚至不用static,因为内部链接已经由const隐含[仅在c++中]。

不要认为“哪个总是最好的”有一个答案,但是,正如马蒂厄所说

静态常量

类型安全。我对#define最大的不满是,在Visual Studio中调试时,你不能看到变量。它给出一个无法找到符号的错误。

这取决于你需要这个值做什么。你(和目前所有人一样)忽略了第三种选择:

Static const int var = 5; #定义var 5 枚举{var = 5};

忽略名字的选择问题,那么:

If you need to pass a pointer around, you must use (1). Since (2) is apparently an option, you don't need to pass pointers around. Both (1) and (3) have a symbol in the debugger's symbol table - that makes debugging easier. It is more likely that (2) will not have a symbol, leaving you wondering what it is. (1) cannot be used as a dimension for arrays at global scope; both (2) and (3) can. (1) cannot be used as a dimension for static arrays at function scope; both (2) and (3) can. Under C99, all of these can be used for local arrays. Technically, using (1) would imply the use of a VLA (variable-length array), though the dimension referenced by 'var' would of course be fixed at size 5. (1) cannot be used in places like switch statements; both (2) and (3) can. (1) cannot be used to initialize static variables; both (2) and (3) can. (2) can change code that you didn't want changed because it is used by the preprocessor; both (1) and (3) will not have unexpected side-effects like that. You can detect whether (2) has been set in the preprocessor; neither (1) nor (3) allows that.

因此,在大多数情况下,优先选择“enum”而不是其他选项。否则,第一个和最后一个要点很可能是控制因素——如果你需要同时满足这两个点,你必须更努力地思考。

如果你问的是c++,那么你每次都应该使用option (1) - static const。