#Define 和 Float 之间的区别?
说这样做有什么区别?
#define NUMBER 10
在什么情况下
float number = 10;
我应该使用其中一种而不是另一种?
What would be the difference between say doing this?
#define NUMBER 10
and
float number = 10;
In what circumstances should I use one over the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将创建一个将由预处理器执行的字符串替换(即在编译期间)。
将在二进制文件的数据段中创建一个浮点并将其初始化为 10。即它将有一个地址并且是可变的。
因此,写入
与写入相同
,而写入
将创建内存访问。
Will create a string replacement that will be executed by the preprocessor (i.e. during compilation).
Will create a float in the data-segment of your binary and initialize it to 10. I.e. it will have an address and be mutable.
So writing
will be the same as writing
whereas writing
will create a memory-access.
正如 Philipp 所说,#define 形式在编译之前的预处理阶段在代码中创建一个替换。由于
#define
不是像number
这样的变量,因此您的定义会在编译时硬写入可执行文件中。如果您所代表的东西确实是一个常量,不需要在运行时从某处计算或读取,并且在运行时不会改变,那么这是可取的。#defines
对于使代码更具可读性非常有用。假设您正在进行物理计算 - 而不是在需要使用重力加速度常数的任何地方都将 0.98f 放入代码中,您可以在一个地方定义它,这样可以提高代码的可读性:编辑
很惊讶回来找到我的答案,发现我没有提到为什么你不应该使用
#define
。通常,您希望避免使用
#define
并使用实际类型的常量,因为#define
没有作用域,并且类型对 IDE 和编译器都有好处。另请参阅此问题和接受的答案:什么是在 Objective-C 中创建常量的最佳方式
As Philipp says, the
#define
form creates a replacement in your code at the preprocessing stage, before compilation. Because the#define
isn't a variable likenumber
, your definition is hard-baked into your executable at compile time. This is desirable if the thing you are repesenting is a truly a constant that doesn't need to calculated or read from somewhere at runtime, and which doesn't change during runtime.#defines
are very useful for making your code more readable. Suppose you were doing physics calculations -- rather than just plonking 0.98f into your code everywhere you need to use the gravitational acceleration constant, you can define it in just one place and it increases your code readability:EDIT
Surprised to come back and find my answer and see I didn't mention why you shouldn't use
#define
.Generally, you want to avoid
#define
and use constants that are actual types, because#define
s don't have scope, and types are beneficial to both IDEs and compilers.See also this question and accepted answer: What is the best way to create constants in Objective-C
“#Define”实际上是一个预处理器宏,在程序启动之前运行,对整个程序有效。
Float 是在程序/块内部定义的数据类型,仅在程序/块内部有效。
"#Define" is actually a preprocessor macro which is run before the program starts and is valid for the entire program
Float is a data type defined inside a program / block and is valid only within the program / block.