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

后端 未结 9 1111
你的背包
你的背包 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:42

    The size of returned type is calculated at compile time, there is no runtime overhead

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

    You said it yourself: 'sizeof' is not a function. It is a built-in operator with special syntax and semantics (see the previous responses). To remember better that it is not a function, you might want to get rid of the habit to use superfluous braces and prefer to use the "braceless" 'sizeof' with expressions as in the following example

    printf("%d\n", sizeof ++i);
    

    This is exactly equivalent to your original version.

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

    sizeof is an operator, not a function.

    It's usually evaluated as compile time - the exception being when it's used on C99-style variable length arrays.

    Your example is evaluating sizeof(int), which is of course known at compile time, so the code is replaced with a constant and therefore the ++ doesn't exist at run-time to be executed.

    int i=0;
    cout << sizeof(++i) << endl;
    cout << i << endl;
    

    It's also worth noting that since it's an operator, it can be used without the brackets on values:

    int myVal;
    cout << sizeof myVal << endl;
    cout << sizeof(myVal) << endl;
    

    Are equivalent.

    0 讨论(0)
提交回复
热议问题