Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

what's the mechanism of sizeof() in C/C++?

It seems sizeof is not a real function?

for example, if you write like this:

int i=0;
printf("%d
", sizeof(++i));
printf("%d
", i);

You may get output like:

4
0

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

So, the compiler put directly the constant "4" as parameters of printf add call it. Then what does sizeof do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You know, there's a reason why there are standard documents (3.8MB PDF); C99, section 6.5.3.4, §2:

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.


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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...