calling sizeof on a function call skips actually calling the function!}

好久不见. 提交于 2019-12-01 17:00:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!