Application rules and Traps analysis of C + + sizeof

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.