为什么C常量不能以short类型存储
正如标题所暗示的,我不明白为什么会这样。
代码:
#include <stdio.h>
#define try 32
int main(void)
{
printf("%ld\n" , sizeof try);
return 0;
}
问题:
1.) 当我尝试使用 sizeof
运算符获取存储大小时,常量 try 存储在中,我得到 4,即 32 位。
2.) 为什么 C 不将它存储在 16 位 short
中,因为它足够大来容纳它。
3.) 有什么方法可以使常量以 short
类型存储吗?
感谢您阅读我的问题,非常感谢。
As the title implies, I don't understand why it is like that.
The Code:
#include <stdio.h>
#define try 32
int main(void)
{
printf("%ld\n" , sizeof try);
return 0;
}
The Question:
1.) When I try using sizeof
operator to get the size of storage the constant try
is stored in, I get 4 which is 32-bits.
2.) Why doesn't C store it in 16-bits short
since it is large enough to hold it.
3.) Is there any ways to make a constant be stored in short
type?
Thank you for reading my question, Much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您误解了 C 预处理器。 C 预处理器仅执行字符串替换 - 它不了解类型。 “32”将根据应用于插入它的上下文的语言规则进行解释 - 通常为
int
。为了使您定义的值始终被视为短值,您可以这样做:
另请参阅:如何用 C++ 编写简短的文字?
You misunderstand the C preprocessor. The C preprocessor simply performs string substitution - it has no knowledge of types. The '32' will get interpreted according to the language rules applying to the context where it gets inserted - typically, as an
int
.To make your defined value always be seen as a short, you could do:
See also: How do I write a short literal in C++?
声明的常量可能就是您正在寻找的:
这通常是首选,因为我相信如果不进行优化(甚至可能进行优化),编译器不会尝试将任何数据类型放入最小数量的可寻址字节中。
Declared constants are probably what you are looking for:
This is typically preferred as I believe without optimizations (or maybe even with) the compiler will not try to fit any data type into the smallest number of addressable bytes.
你所说的常量定义实际上是一个宏定义,它表示标签 try 在预处理时将被 32 替换。
因此编译器会理解它的 sizeof(32) 没有指定任何类型。因此它获得与系统相关的默认类型。
要创建一个短常量,您必须在定义的宏中转换您的值,或者将其初始化为全局常量,如下所示:
What you call a constant definition is in fact a macro definition that says the label try will be replaced by 32 at preprocessing time.
So the compiler will understand it sizeof(32) which does not have any type specified. So it gets the default types which is system dependent.
To make a short constant you will have either to cast your value in the defined macro or initialize it as a global one like follow:
我会对此进行尝试,但我不完全确定我是否正确,
因为 #define 只是告诉预处理器将 try 替换为您的数字,它的作用就好像它只是一个值。在您的特定计算机上,该值存储在内存中的 4 字节空间中。我能想到的唯一解决方案是使用具有使用默认 16 位大小的 int 架构的机器。
即使它是一个短整型,由于对齐的原因,它仍然可能会占用内存中的 4 个字节,但这实际上取决于情况。
I will take a crack at this, but I'm not entirely sure if I'm correct
Since #define is just telling the preprocessor to replace try with your number, it's acting as if it was just a value. On your specific machine, that value is being stored in a 4 byte space in memory. The only solution to this I can think of is to use a machine with an architecture that uses a default 16 bit size for an int.
Even if it was a short, it might still occupy 4 bytes in memory because of alignment, but it really depends.