Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

sizeof

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

like image 982
Chethan Ravindranath Avatar asked Apr 26 '12 06:04

Chethan Ravindranath


2 Answers

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

like image 108
Cat Plus Plus Avatar answered Oct 06 '22 23:10

Cat Plus Plus


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.

like image 45
Joni Avatar answered Oct 07 '22 00:10

Joni