As the operand of sizeof
operator is not evaluated, you can do this:
int f(); //no definition, which means we cannot call it
int main(void) {
printf("%d", sizeof(f()) ); //no linker error
return 0;
}
Online demo : http://ideone.com/S8e2Y
That is, you don't need define the function f
if it is used in sizeof
only. This technique is mostly used in C++ template metaprogramming, as even in C++, the operand of sizeof
is not evaluated.
Why does this work? It works because the sizeof
operator doesn't operate on value, instead it operates on type of the expression. So when you write sizeof(f())
, it operates on the type of the expression f()
, and which is nothing but the return type of the function f
. The return type is always same, no matter what value the function would return if it actually executes.
In C++, you can even this:
struct A
{
A(); //no definition, which means we cannot create instance!
int f(); //no definition, which means we cannot call it
};
int main() {
std::cout << sizeof(A().f())<< std::endl;
return 0;
}
Yet it looks like, in sizeof
, I'm first creating an instance of A
, by writing A()
, and then calling the function f
on the instance, by writing A().f()
, but no such thing happens.
Demo : http://ideone.com/egPMi
Here is another topic which explains some other interesting properties of sizeof
:
printf("%d and ", sizeof(x++)); // note 1
causes UB, why do you expect any meaningful output? Please read theprintf()
manpage or the C standard sections aboutprintf()
/fprintf()
. – Halftruth