Understanding of function value passing and reference passing

Source: Internet
Author: User

In C ++, calling a function involves the following processes:

1. Import the status of the parent function to the stack.

2. The system requests a memory segment as the stack space of the sub-function.

3. Call the copy constructor of the sub-function parameters, and the new object is pushed into the stack of the sub-function.


Of course, there are still many processes in it, which are not described in detail here.

Therefore, when the sub-function modifies the value of the function parameter, the value in the parent function is not modified. (Because it is modified to copy the new object after the construction, it is not the original object)

This is the value transfer.

Void fun (int B) {B = 10;} int main () {int A = 5; fun (a); // at this time a = 5 ;}



When the parameter declaration of your sub-function is a reference object,

3. The process is the process of value assignment. For example, Int & B =;

At this time, A and B are equivalent to establishing a co-existence relationship. (In layman's terms)

When B is passed to a subfunction, the value of B is modified in the subfunction, and the value of A in the parent function is also modified. (Because there is a reference to this layer)

This is to pass the reference.

Void fun (Int & B) {B = 10;} int main () {int A = 5; fun (a); // at this time a = 10 ;}


Understanding of function value passing and reference passing

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.