sizeof 在编译时起作用吗?
我运行了这个示例程序。
const int x = 5;
int main(int argc, char** argv)
{
int x[x];
int y = sizeof(x) / sizeof(int);
return 0;
}
y 的值为 5。
但这怎么可能呢?因为当我调试时,x的值为5,所以x的大小为4,int的大小为4。并且y的值应该是不同的。
我缺少什么?
I ran this sample program.
const int x = 5;
int main(int argc, char** argv)
{
int x[x];
int y = sizeof(x) / sizeof(int);
return 0;
}
The Value of y is 5.
But how is this possible? Because when I debugged, the value of x was 5, so the size of x is 4 and size of int is 4. And value of y should have been different .
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
sizeof(x)
指的是具有5
个int
类型元素的数组。因此输出。如果您没有重载名称
x
,代码会更容易理解。从技术上讲,这里有一个可变长度数组,即 VLA。这是因为 C
const
实际上意味着只读,并且必须在运行时进行评估。因此,在这种情况下,sizeof 是在运行时评估的。如果您使用文字来调整数组的大小,即
int x[5];
,那么sizeof
将在编译时进行评估。如果代码已编译为 C++,则 const 将是真正的 const,因此可在编译时进行评估。
sizeof(x)
refers to the array which has5
elements of typeint
. Hence the output.The code would be a lot easier to understand if you didn't overload the name
x
.Technically what you have here is a variable length array, a VLA. This is because C
const
actually means read-only and has to be evaluated at run time. Hencesizeof
, in this case, is evaluated at runtime.If you had used a literal to size your array instead, i.e.
int x[5];
thensizeof
would have been evaluated at compile time.If the code had been compiled as C++ then the const would be a true const, and so available for evaluation at compile time.
这里正在进行变量隐藏。您的代码大致相当于:
那么就更清楚了:
sizeof(x)==4
,x==5
,sizeof(x2)==20
代码>.You have variable hiding going on here. Your code is roughly equivalent to:
Then it's clearer:
sizeof(x)==4
,x==5
,sizeof(x2)==20
.x 的类型为 int[5]。因此,大小为5*sizeof(int)。 sizeof 是一个运算符,而不是函数或宏。
这就是为什么当人们声称 C 数组只是指针但不幸的是你不能传递数组时,有些人会感到恼火。您只能传递指向其第一个元素的指针,并且您会丢失此信息。
x is of type int[5]. Therefore, the size is 5*sizeof(int). sizeof is an operator, not a function or a macro.
This is why some people get annoyed when people claim that C arrays are just pointers, but unfortunately you can't pass an array. You can only pass a pointer to it's first element, and you loose this information.
由于 int x 是 const,因此这是一个固定大小的数组。 Sizeof 是在编译时计算的。
正如定义清楚所示,
x
有五个元素。它的大小是 5 * sizeof(int)。这是GCC,我使用printf打印出y的值:
分配的空间和y的值都被编译为常量。
另外,从标准来看:
Since int x is
const
, this is a fixed size array. Sizeof is calculated at compilation time.x
has five elements, as the definition clearly shows. It's size is 5 * sizeof(int).This is GCC, I use printf to print out the value of y:
Both the allocated space and the value of y is compiled as constants.
Also, from the standard: