Fetch address and reference in C + +

Source: Internet
Author: User

The use of & identifiers for both addresses and references makes it easy to misunderstand.

In the case of C + +. References are only knowledge in C + +, and the address is shared.

Take address:

In line 6th I define a pointer to the INT type P, use &a to get the address of a and assign the address of a to it, that is, p points to the space where A is located.

In line 7th, take the value of P pointing to the space (*: There is a high-end name called the dereference) output.


Reference:

In line 6th I define a reference B and assign a to B. The essence is to give a a small name B. The A operation is the B operation, if the value of B is changed (eg. B=20), the value of a also changes accordingly (a also equals 20)

From lines 7th and 8, I can say that the values of a and B are equal and the addresses are the same. So the reference is not space-intensive, only the individual name.


The reference and fetch address may also be confused when the function is called:

First look at the function prototypes of line 2nd and 3. The function of two functions is to exchange two numbers. The two parameters of swap1 are pointers, and SWAP2 's formal parameters are two references.

Take a look at line 8th, line 9th, call Swap1 when the time passed two address to it (X=&A,Y=&B), that is, X points to a space, Y points to B space. When I call SWAP2, we pass two references to it (X=A,Y=B), that is, X is just an alias of a, Y is an alias of B, but it all represents the same space.


When a function is called, the reference is more efficient and simpler than the pointer. The copy address requires overhead, and the reference is directly optimized by the compiler, because the pointer is the actual or the value of the pass-through call. There are times when you need a two-level pointer, using a pointer reference will make the problem a lot easier, I have encountered the operation of the tree, you can feel it.

Fetch address and reference in C + +

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.