C + + arguments and parameters Exchange variable values

Source: Internet
Author: User

1. Call-to-value mechanism (Call-by-value machanism)

(1). The value of the argument is inserted at the formal parameter position. If the argument is a variable, only the value of the variable is inserted, not the variable itself.

(2). The value call parameter is a local variable. When the function is called, the parameter of the function is initialized to the value of the argument.

eg

void swap (int x, int y)

{

int temp;

temp = x;

x = y;

y = temp;

}

Main ()

{

int a = 1, b = 2;

cout << "a =" << a << "b=" << b << "\ n";

Swap (A, b);

return 1;

}

Operation Result:

A = 1 B = 2

A = 1 B = 2

Description: No occurrence worth exchanging

2. Invoking a referral mechanism

(1). Replace the parameter with the memory location of the argument. Because program variables are implemented as memory locations, these memory locations are variables. That is, the variable itself is inserted at the formal parameter position, not the value of the variable.

(2). The reference call parameter is replaced by the memory location of the argument, so the variable will change if the memory location is modified in the function body.

eg

eg

void swap (int &x, int &y)

{

int temp;

temp = x;

x = y;

y = temp;

}

The result that appears:

A = 1 B = 2

A = 2 B = 1

For the above two examples explained in detail:

In the first example, when the swap function is called, the values of A and B are passed to X and Y, where x and y are relative to the copy of A and B, and the change of the copy does not change the value of the variable itself.

In the second example, the SWAP function defines a reference to X, Y, when the main function calls swap, x and Y are references to A and b respectively, at which point X and a represent the same variable, y and b represent the same variable, and when x and Y are exchanged, A and B are exchanged, which makes two variables worth exchanging.

C + + arguments and parameters Exchange variable values

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.