1, what is sizeof
First look at the definition of sizeof on MSDN:
The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types) . This keyword returns a value of type size_t.
See the word return, is not the thought of the function? Wrong, sizeof is not a function, have you ever seen a function pass an argument without parenthesis? sizeof can, so sizeof is not a function. Someone on the internet says sizeof is a unary operator, but I don't think so, because sizeof is more like a special macro, it's evaluated at compile time. As an example:
cout<<sizeof(int)<<endl; // 32位机上int长度为4
cout<<sizeof(1==2)<<endl; // == 操作符返回bool类型,相当于 cout<<sizeof(bool)<<endl;
has been translated in the compilation phase:
cout<<4<<endl;
cout<<1<<endl;
Here's a trap, look at the following program:
int a = 0;
cout<<sizeof(a=3)<<endl;
cout<<a<<endl;
Why is the output 4,0 rather than the desired 4,3??? Lies in the features that sizeof deals with during the compile phase. Since sizeof cannot be compiled into machine code, the contents of the sizeof range, that is (), cannot be compiled, but replaced by a type. The = operator returns the type of the left-hand operand, so a=3 is equivalent to int, and the code is replaced by:
int a = 0;
cout<<4<<endl;
cout<<a<<endl;
Therefore, it is impossible for sizeof to support chained expressions, which is not the same as a unary operator.
Conclusion: Do not treat sizeof as a function, nor as a unary operator, and treat him as a special compilation preprocessing.