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

后端 未结 9 1110
你的背包
你的背包 2020-12-09 13:16

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);


        
相关标签:
9条回答
  • 2020-12-09 13:26

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

    0 讨论(0)
  • 2020-12-09 13:30

    It is replaced with the constant (4 in your case) at compile time. Because it takes 4 bytes to hold an int on your platform.

    And your code will not compile, instead of giving you any output ;-) Because of sizoef ;-)

    0 讨论(0)
  • 2020-12-09 13:31

    Exactly what it's meant to do: puts directly the constant "the size of the variable/constant/type/etc" into the code

    0 讨论(0)
  • 2020-12-09 13:32

    Sizeof analyzes the passed expression to find its type. It then returns the size of the type.

    Because the size of a type is always known at compile time, it is put into the machine code as a constant.

    0 讨论(0)
  • 2020-12-09 13:33

    sizeof() returns the size in bytes of whatever you pass as an argument to it. In a 32-bit architecture sizeof(int) would return 4, while sizeof(char) would return 1.

    0 讨论(0)
  • 2020-12-09 13:39

    In C++ sizeof() calculates size of the type of the expression within it and replaces the whole "sizeof() function call" with a constant during compilation.

    The expression within sizeof() is never evaluated during the program execution. And it may not even be a type name. Check these examples out:

    struct X { int i; double j;};
    int call_to_undefined_function();
    
    sizeof(10/0);
    sizeof( ((struct X*)NULL)->j );
    sizeof( call_to_undefined_function() + 100 );
    sizeof( call_to_undefined_function() + 100.0 );
    sizeof( double() / int() );
    
    0 讨论(0)
提交回复
热议问题