#define 值的大小
如果值定义为
#define M_40 40
大小与 short
相同(2 字节)还是 char
( 1 字节)还是 int
(4 字节)?
大小是否取决于您是 32 位还是 64 位?
If a value is defined as
#define M_40 40
Is the size the same as a short
(2 bytes) or is it as a char
(1 byte) or int
(4 bytes)?
Is the size dependent on whether you are 32-bit or 64-bit?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
#define
没有大小,因为它不是类型,而是 C++ 代码中的纯文本替换。#define
是一个预处理指令,它在代码开始编译之前运行。替换后 C++ 代码的大小是 C++ 表达式或代码的大小。例如,如果您使用
L
后缀(如102L
),那么它会被视为 long,否则没有后缀,只是一个 int。所以在 x86 和 x64 上可能是 4 个字节,但这取决于编译器。也许 C++ 标准的整数文字部分将为您清除它(C++03 标准的第 2.13.1-2 节):
#define
has no size as it's not a type but a plain text substitution into your C++ code.#define
is a preprocessing directive and it runs before your code even begins to be compiled .The size in C++ code after substitution is whatever the size is of what C++ expression or code you have there. For example if you suffix with
L
like102L
then it is seen a long, otherwise with no suffix, just an int. So 4 bytes on x86 and x64 probably, but this is compiler dependent.Perhaps the C++ standard's Integer literal section will clear it up for you (Section 2.13.1-2 of the C++03 standard):
在所有计算和赋值中,普通整数将被隐式转换为
int
。#define 只是告诉预处理器用其他东西替换对符号的所有引用。这与在代码上执行全局查找替换并将
M_40
替换为40
相同。A plain integer is going to be implicitly cast to
int
in all calculations and assignments.#define
simply tells the preprocessor to replace all references to a symbol with something else. This is the same as doing a global find-replace on your code and replacingM_40
with40
.具体来说,#define 值没有大小。这只是文本替换。这取决于替换位置(以及替换内容)的上下文。
在您的示例中,如果使用
M_40
,编译将看到40
,并且通常将其视为int
。但是,如果我们有:
它将被视为 long。
A #define value has no size, specifically. It's just text substitution. It depends on the context of where (and what) is being substituted.
In your example, where you use
M_40
, the compile will see40
, and usually treat it as inint
.However, if we had:
It will be treated as a long.
预处理器宏在编译的预处理阶段实际上被交换。
例如,
代码将被交换
当编译器看到代码时, 。它本身没有自己的尺寸
Preprocessor macros get literally swapped in during the preprocess stage of the compilation.
For example the code
will get swapped for
when the compiler sees it. It does not have a size of its own as such
预处理器仅执行简单的文本替换,因此常量位于
#define
中这一事实并不重要。 C 标准规定的是“每个常量都应该有一个类型,并且常量的值应该在其类型的可表示值的范围内”。 C++ 可能不会有太大变化。The preprocessor just does simple text substitution, so the fact that your constant is in a
#define
doesn't matter. All the C standard says is that "Each constant shall have a type and the value of a constant shall be in the range of representable values for its type." C++ is likely to not vary too much from that.