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

static const int var = 5;

or

#define var 5

or

enum { var = 5 };

当前回答

如果你可以使用它,静态const有很多优点。它遵循正常的作用域原则,在调试器中可见,并且通常遵守变量所遵循的规则。

然而,至少在最初的C标准中,它实际上不是一个常数。如果你使用#define var 5,你可以写int foo[var];作为一个声明,但你不能这样做(除非作为一个编译器扩展“与静态const int var = 5;;在c++中不是这样,静态const版本可以在#define版本可以使用的任何地方使用,我相信C99也是如此。

但是,永远不要用小写名称命名#define常量。它将覆盖该名称的任何可能使用,直到翻译单元结束。宏常量应该在实际上属于它们自己的名称空间中,传统上都是大写字母,可能还有一个前缀。

其他回答

一般来说:

static const

因为它尊重作用域并且是类型安全的。

我能看到的唯一警告是:如果您希望变量可能在命令行上定义。还有另一种选择:

#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

尽可能使用类型安全的替代方法,而不是宏/省略号。

如果你真的需要使用宏(例如,你想要__FILE__或__LINE__),那么你最好非常小心地命名你的宏:在它的命名约定中,Boost推荐所有大写字母,以项目的名称(这里是BOOST_)开头,而仔细阅读库,你会注意到这(通常)后面是特定区域(库)的名称,然后是一个有意义的名称。

它通常会产生很长的名字:)

虽然这个问题是关于整数的,但值得注意的是,如果需要常量结构或字符串,#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.

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

例如,

struct mystruct {
    int var;
};

#define var 5

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

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

一个简单的区别:

在预处理时,常量被替换为它的值。 因此,不能将解引用操作符应用于定义,但可以将解引用操作符应用于变量。

如您所料,define比static const更快。

例如,有:

#define mymax 100

你不能做printf("address of constant is %p",&mymax);

但是有

const int mymax_var=100

你可以做printf("address of constant is %p",&mymax_var);

更清楚地说,define在预处理阶段被它的值替换,因此程序中没有存储任何变量。我们只有使用define的程序文本段的代码。

然而,对于static const,我们有一个被分配到某处的变量。对于gcc,静态const分配在程序的文本段中。

上面,我想讲的是引用操作符,所以用引用替换解引用。

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

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