The sizeof call to the function call skips the actual function call!}

I happened to stumble over 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 him to print 20, then 4. But he just prints 4. Why is this so? Is it wrong to optimize a function that has a side effect (print to IO / file, etc.)?

+7
source share
5 answers

sizeof is a compile-time operator, and the operand is never evaluated.

+13
source

sizeof actually an operator and is evaluated at compile time.

The compiler can evaluate it because the size of the return type x fixed; it cannot change during program execution.

+4
source

sizeof result is computed when compiling time in C ++. therefore there is a call to function x (20)

+2
source

sizeof() sets the size of the data type. In your case, there is no need to call a function to get the data type.

I suspect sizeof also does this business at compile time rather than run time ...

+2
source

Let me quote C ++ 03 standard, # 5.3.3.

The sizeof operator gives the number of bytes in an object representing its operand. An operand is either an expression that is not evaluated , or a type identifier in brackets.

+2
source

All Articles