Code-
#include <bits/stdc++.h>
using namespace std;
int *fun()
{ static int a;
++a;
cout<<"value of a = "<<a<<endl;
return &a;
}
int main() {
cout<<"simple call \n";
fun();
cout<<"calling inside sizeof \n";
cout<<sizeof(fun())<<endl;
cout<<"calling inside pow \n";
cout<<pow(2,*fun())<<endl;
return 0;
}
Output-
simple call
value of a = 1
calling inside sizeof
8
calling inside pow
value of a = 2
4
My doubt is how sizeof operator calculate size of return type of function. I assume function is first called then it return address to it's static variable and sizeof operator is operated on that value. But here, it's directly printing sizeof pointer. And if I use same fun inside pow() it is first called and then further calculation is done.
No, sizeof
never evaluates its operands (except for C variable length arrays but, since this is a C++ question, that's irrelevant). From C++17 [expr.sizeof]
:
The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 8), or a parenthesized type-id.
In your case, since fun()
returns int *
(thew compiler knows this because you told it so), it's as if you had asked for sizeof(int *)
.