使用 ++在 sizeof 关键字内
可能的重复:
C/C++中sizeof()的机制是什么?
我是一所大学的助教,最近,我向我的本科生展示了我发现的 C 谜题中的以下 C 代码:
int i = 5;
int j = sizeof(i++);
printf("%d\n%d\n", i, j);
我只有一个问题:为什么 i 的输出等于 5,而不是 6? ++ 是否被简单地忽略了?这是怎么回事?谢谢!
Possible Duplicate:
what's the mechanism of sizeof() in C/C++?
Hi,
I'm a TA for a university, and recently, I showed my undergraduate students the following C code from a C puzzle I found:
int i = 5;
int j = sizeof(i++);
printf("%d\n%d\n", i, j);
I just have one question: why is the output for i equal to 5, not 6? Is the ++ simply disregarded? What's going on here? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
sizeof 中的表达式不会被求值——只使用它的类型。在本例中,类型为 int,即 i++ 计算后将产生的结果。这种行为是必要的,因为 sizeof 实际上是一种编译时操作(因此其结果可用于调整数组大小等操作),而不是运行时操作。
The expression in a sizeof is not evaluated - only its type is used. In this case, the type is int, the result of what i++ would produce if it were evaluated. This behavior is necessary, as sizeof is actually a compile-time operation (so its result can be used for things like sizing arrays), not a run-time one.
sizeof 运算符在编译时评估。 sizeof(i++) 基本上将编译器读取为 sizeof(int) (丢弃 ++)。
为了演示这一点,您可以查看小程序的汇编视图:
正如您在标记行中看到的,整数 (4) 的大小已经存在并且刚刚加载到 i 中。当程序运行时,它不会被评估甚至计算。
The sizeof operator is evaluated at compile-time. sizeof(i++) basically reads to the compiler as sizeof(int) (discarding the ++).
To demonstrate this you can look at the assembly view of your little program:
As you can see in the marked line, the size of the integer (4) is already there and just loaded into i. It is not evaluated or even calculated when the program runs.
是的,
sizeof
内部仅针对类型进行评估。Yes, inside
sizeof
is only evaluated for the type.主要原因是
sizeof
不是一个函数
,它是一个运算符
。除非存在可变长度数组,否则它主要在编译时进行评估。由于int
的大小可以在编译时计算,因此,它返回4
。The main reason is that
sizeof
is not afunction
, it is anoperator
. And it is mostly evaluated at compile-time unless there is a variable length array. Sinceint
's size can be evaluated at compile-time, therefore, it returns4
.sizeof 不计算其中的表达式,仅计算类型。
我们要记住的是,sizeof 不是一个函数,而是一个编译时运算符,因此,它不可能评估其内容。
sizeof does not evaluate the expression inside it, only the type.
What we have keep in mind is that sizeof is not a function but a compile time operator, so, it is impossible for it evaluate its content.