#define和const之间有什么区别? [英] What is the difference between #define and const?

查看:124
本文介绍了#define和const之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复项:

为什么有人使用#define来定义常量?



C ++ - 枚举vs.常数与#define

使用 #define const 之间的区别创造一个常数?是否有任何性能优势超过其他?当然我喜欢使用 const ,但如果它有合适的优点,我会考虑 #define #define 指令是预处理程序

What is the difference between using #define and const for creating a constant? Does any have a performance advantage over the other? Naturally I prefer using the const but I'm going to consider the #define if it has suitable advantages.

推荐答案

强>指令;预处理器在编译器甚至看到宏之前,通过其主体替换这些宏。

The #define directive is a preprocessor directive; the preprocessor replaces those macros by their body before the compiler even sees it. Think of it as an automatic search and replace of your source code.

一个const变量声明在语言中声明一个实际的变量,你可以使用... well,像一个真正的变量:获取它的地址,传递它,使用cast,它转换等。

A const variable declaration declares an actual variable in the language, which you can use... well, like a real variable: take its address, pass it around, use cast it, convert it, etc.

哦,性能:也许你认为避免声明的变量节省时间和空间,但是任何明智的编译器优化级别都没有差别,因为常量值已经在编译时被替换和折叠。但是你获得了类型检查和让你的代码知道调试器的巨大优势,所以没有理由不使用const变量。

Oh, performance: Perhaps you're thinking that avoiding the declaration of a variable saves time and space, but with any sensible compiler optimisation levels there will be no difference, as constant values are already substituted and folded at compile time. But you gain the huge advantage of type checking and making your code known to the debugger, so there's really no reason not to use const variables.

这篇关于#define和const之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆