在C语言中,下列语句中使用哪个更好?
static const int var = 5;
or
#define var 5
or
enum { var = 5 };
在C语言中,下列语句中使用哪个更好?
static const int var = 5;
or
#define var 5
or
enum { var = 5 };
当前回答
我们查看了MBF16X上生成的汇编代码…这两种变体产生相同的算术运算代码(例如ADD Immediate)。
所以const int是类型检查的首选,而#define是旧风格。也许它是特定于编译器的。因此,请检查生成的汇编程序代码。
其他回答
我不确定我是否正确,但在我看来,调用#defined value比调用任何其他正常声明的变量(或const value)快得多。 这是因为当程序运行时,它需要使用一些正常声明的变量,它需要跳转到内存中的确切位置来获得该变量。
相反,当它使用#defined value时,程序不需要跳转到任何已分配的内存,它只是接受该值。如果#define myValue 7和调用myValue的程序,它的行为与只调用7时完全相同。
一般来说:
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_)开头,而仔细阅读库,你会注意到这(通常)后面是特定区域(库)的名称,然后是一个有意义的名称。
它通常会产生很长的名字:)
如果你有mystruct.var这样的东西,#define var 5会给你带来麻烦。
例如,
struct mystruct {
int var;
};
#define var 5
int main() {
struct mystruct foo;
foo.var = 1;
return 0;
}
预处理器将取代它,代码将无法编译。因此,传统的编码风格建议所有常量#定义都使用大写字母以避免冲突。
使用const而不是#define总是更好。这是因为const是由编译器处理的,而#define是由预处理器处理的。这就像#define本身不是代码的一部分(粗略地说)。
例子:
#define PI 3.1416
符号名称PI可能永远不会被编译器看到;它可能在源代码到达编译器之前被预处理器删除。因此,名称PI可能无法进入符号表。如果在编译过程中遇到涉及使用常量的错误,这可能会令人困惑,因为错误消息可能指向3.1416,而不是PI。如果圆周率定义在一个你没有写的头文件中,你就不知道3.1416是从哪里来的。
这个问题也可能在符号调试器中突然出现,因为您正在编程的名称可能不在符号表中。
解决方案:
const double PI = 3.1416; //or static const...
虽然这个问题是关于整数的,但值得注意的是,如果需要常量结构或字符串,#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.