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

static const int var = 5;

or

#define var 5

or

enum { var = 5 };

当前回答

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

其他回答

我写了一个快速测试程序来证明其中的一个区别:

#include <stdio.h>

enum {ENUM_DEFINED=16};
enum {ENUM_DEFINED=32};

#define DEFINED_DEFINED 16
#define DEFINED_DEFINED 32

int main(int argc, char *argv[]) {

   printf("%d, %d\n", DEFINED_DEFINED, ENUM_DEFINED);

   return(0);
}

这个编译带有以下错误和警告:

main.c:6:7: error: redefinition of enumerator 'ENUM_DEFINED'
enum {ENUM_DEFINED=32};
      ^
main.c:5:7: note: previous definition is here
enum {ENUM_DEFINED=16};
      ^
main.c:9:9: warning: 'DEFINED_DEFINED' macro redefined [-Wmacro-redefined]
#define DEFINED_DEFINED 32
        ^
main.c:8:9: note: previous definition is here
#define DEFINED_DEFINED 16
        ^

注意,当define给出警告时,enum给出一个错误。

虽然这个问题是关于整数的,但值得注意的是,如果需要常量结构或字符串,#define和enum是无用的。它们通常都作为指针传递给函数。(对于字符串,它是必需的;有了结构,效率就高多了。)

As for integers, if you're in an embedded environment with very limited memory, you might need to worry about where the constant is stored and how accesses to it are compiled. The compiler might add two consts at run time, but add two #defines at compile time. A #define constant may be converted into one or more MOV [immediate] instructions, which means the constant is effectively stored in program memory. A const constant will be stored in the .const section in data memory. In systems with a Harvard architecture, there could be differences in performance and memory usage, although they'd likely be small. They might matter for hard-core optimization of inner loops.

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

例子:

#define PI 3.1416

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

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

解决方案:

const double PI = 3.1416; //or static 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++中]。

如果你有mystruct.var这样的东西,#define var 5会给你带来麻烦。

例如,

struct mystruct {
    int var;
};

#define var 5

int main() {
    struct mystruct foo;
    foo.var = 1;
    return 0;
}

预处理器将取代它,代码将无法编译。因此,传统的编码风格建议所有常量#定义都使用大写字母以避免冲突。