问题
I happened to stumble across this piece of code.
int x(int a){
std::cout<<a<<std::endl;
return a + 1;
}
int main()
{
std::cout<<sizeof(x(20))<<std::endl;
return 0;
}
I expected it to print 20 followed 4. But it just prints 4. Why does it happen so? Isn't it incorrect to optimize out a function, that has a side effect (printing to IO/file etc)?
回答1:
sizeof
is a compile-time operator, and the operand is never evaluated.
回答2:
sizeof
is actually an operator and it is evaluated in compile-time.
The compiler can evaluate it because the size of the return type of x
is fixed; it cannot change during program execution.
回答3:
result of sizeof is computed in compiling time in C++. so there has of function call to x(20)
回答4:
sizeof()
gives the size of the datatype. In your case it doesn't need to call the function to obtain the datatype.
I suspect sizeof also does it's business at compile time rather than runtime...
回答5:
Let me quote c++03 standard, #5.3.3.
The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is not evaluated, or a parenthesized type-id.
来源:https://stackoverflow.com/questions/10328554/calling-sizeof-on-a-function-call-skips-actually-calling-the-function