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

static const int var = 5;

or

#define var 5

or

enum { var = 5 };

当前回答

在C语言中?在C语言中,正确的答案是:使用#define(或者,如果合适,使用enum)

虽然具有const对象的作用域和类型属性是有益的,但实际上C中的const对象(与c++相反)并不是真正的常量,因此在大多数实际情况下通常是无用的。

所以,在C语言中,选择应该取决于你计划如何使用常数。例如,你不能使用const int对象作为case标签(而宏可以)。你不能使用const int对象作为位域宽度(而宏可以)。在C89/90中,你不能使用const对象来指定数组大小(而宏可以)。即使在C99中,当你需要一个非vla数组时,你也不能使用const对象来指定数组大小。

如果这对你很重要,那么它将决定你的选择。大多数时候,你别无选择,只能在C中使用#define。不要忘记另一个选择,它在C - enum中产生真正的常量。

在c++中,const对象是真正的常量,所以在c++中,最好使用const变体(但在c++中不需要显式的静态)。

其他回答

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

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。

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

静态常量

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

在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++中]。

C中const的另一个缺点是不能在初始化另一个const时使用该值。

static int const NUMBER_OF_FINGERS_PER_HAND = 5;
static int const NUMBER_OF_HANDS = 2;

// initializer element is not constant, this does not work.
static int const NUMBER_OF_FINGERS = NUMBER_OF_FINGERS_PER_HAND 
                                     * NUMBER_OF_HANDS;

即使这对const也不起作用,因为编译器不会将其视为常量:

static uint8_t const ARRAY_SIZE = 16;
static int8_t const lookup_table[ARRAY_SIZE] = {
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // ARRAY_SIZE not a constant!

我很乐意在这些情况下使用类型化的const,否则…

我不确定我是否正确,但在我看来,调用#defined value比调用任何其他正常声明的变量(或const value)快得多。 这是因为当程序运行时,它需要使用一些正常声明的变量,它需要跳转到内存中的确切位置来获得该变量。

相反,当它使用#defined value时,程序不需要跳转到任何已分配的内存,它只是接受该值。如果#define myValue 7和调用myValue的程序,它的行为与只调用7时完全相同。