#定义VS变量 [英] #Define VS Variable
问题描述
我不明白它们之间的区别是什么
I cannot understand what is the difference between:
#define WIDTH 10
和
int width = 10;
使用第一个或第二个有什么好处?
What are the benefits of using the first or the second?
推荐答案
嗯,有很大的不同。您可以更改 width
的值,可以获取其地址,可以要求其大小,依此类推。使用 WIDTH
,它将随处都被常量 10
代替,因此表达式 + + WIDTH
没有任何意义。在另一边,您可以声明带有 WIDTH
个项目的数组,而不能声明带有 width
个项目的数组。
Well, there is a great difference. You can change the value of width
, you can take its address, you can ask for its size and so on. With WIDTH
, it will be just replaced with a constant 10
everywhere, so the expression ++WIDTH
doesn't make any sense. Ono the other side, you can declare an array with WIDTH
items, whereas you cannot declare an array with width
items.
总结一下: WIDTH
的值在编译时是已知的,不能更改。编译器不会为<$ c $ c> WIDTH 分配内存。相反, width
是一个 initial 值为10的变量,其进一步的值在编译时未知;该变量从编译器获取其内存。
Summing it up: the value of WIDTH
is known at compile time and cannot be changed. The compiler doesn't allocate memory for WIDTH
. On the contrary, width
is a variable with initial value 10, its further values are not known at compile time; the variable gets its memory from the compiler.
这篇关于#定义VS变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!