什么是的sizeof()的C / C ++的机制? [英] what's the mechanism of sizeof() in C/C++?
问题描述
看来sizeof的是不是一个真正的功能?
It seems sizeof is not a real function?
例如,如果你写这样的:
for example, if you write like this:
int i=0;
printf("%d\n", sizeof(++i));
printf("%d\n", i);
您可能会得到这样的输出:
You may get output like:
4
0
当你深入到组装code,你会发现某事像这样:
And when you dig into the assemble code, you'll find sth like this:
movl $4, %esi
leaq LC0(%rip), %rdi
xorl %eax, %eax
call _printf
所以,编译器直接就把常数4的printf添加参数调用它。那么,什么是sizeof的怎么办?
So, the compiler put directly the constant "4" as parameters of printf add call it. Then what does sizeof do?
推荐答案
您知道,有一个原因,还有的standard文档(3.8MB PDF); C99,节6.5.3.4,§2:
You know, there's a reason why there are standard documents (3.8MB PDF); C99, section 6.5.3.4, §2:
的的sizeof
运营商得到规模
(字节)的操作数,这可能
是当然pression或括号
命名的类型。的大小被确定
从操作数的类型。该
结果是整数。如果类型的
操作数是可变长度数组
类型,操作数被评估;
否则,操作数是不
评价,其结果是一个整数
恒
在回应ibread的评论,下面是C99的可变长度阵列情况的一个例子:
In response to ibread's comment, here's an example for the C99 variable length array case:
#include <stdio.h>
size_t sizeof_int_vla(size_t count)
{
int foo[count];
return sizeof foo;
}
int main(void)
{
printf("%u", (unsigned)sizeof_int_vla(3));
}
富
的大小是在编译时不再知,并已在运行时确定。生成的汇编看起来很怪异,所以不要问我有关实施细节...
The size of foo
is no longer known at compile-time and has to be determined at run-time. The generated assembly looks quite weird, so don't ask me about implementation details...
这篇关于什么是的sizeof()的C / C ++的机制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!