Pass Reference C

Source: Internet
Author: User

Transferred from: http://myturn.blog.hexun.com/15584978_d.html

#include <iostream>

using namespace Std;

void Swap (int x, int y);

int main (void)

{

int a = 1;

int b = 2;

cout << "a =" << a << "," << "b =" << b << Endl;

Swap (A, b);

cout << "a =" << a << "," << "b =" << b << Endl;

System ("pause");

return 0;

}

One: Value passing

void Swap (int x, int y)

{

int temp = x;

x = y;

y = temp;

}

Output Result:

A = 1, b = 2

A = 1, b = 2

Cause: the Swap (int x, int y) function takes a value pass, and the actual arguments passed in are actually copies of a and b rather than themselves, so changes to the copy do not reflect A and B.

II: Reference Delivery

void Swap (int &x, int &y)

{

int temp = x;

x = y;

y = temp;

}

Output Result:

A = 1, b = 2

A = 2, B = 1

Cause: the Swap (int x, int y) function takes the form of a reference pass, and the actual arguments passed in are actually references to A and B, and the changes to the reference directly reflect A and B.

Three: pointer passing

1. Change the pointer itself

void Swap (int *x, int *y)

{

int *temp = x;

x = y;

y = temp;

}

Calling method: Swap (&a, &b);

Output Result:

A = 1, b = 2

A = 1, b = 2

Cause: the Swap (int x, int y) function takes a pointer pass, and the actual argument passed in is actually a copy of the pointer to A and B, and it changes the copy itself rather than its indirect reference, so it does not affect the value that the pointer points to, A and B.

2. Changing the pointer's indirect reference

void Swap (int *x, int *y)

{

int temp = *x;

*x = *y;

*y = temp;

}

Calling method: Swap (&a, &b);

Output Result:

A = 1, b = 2

A = 2, B = 1

Cause: the Swap (int x, int y) function takes a pointer pass, although the incoming argument is also a copy of the pointer to a and B, but changes the indirect reference to the copy, either the pointer itself or its copy, pointing to the same value, so the change will reflect A and B.

Pass reference C (GO)

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.