Introduction to C + + Classic-Example 5.18-exchanging values by reference

Source: Internet
Author: User

1: In C + +, there are two main ways in which function parameters are passed, that is, value passing and reference passing. Value passing refers to passing a copy of the value of the actual parameter to the calling function when the function is called, so that if the value of the parameter is modified in the calling function, its change will not affect the value of the actual parameter. Whereas reference passing is the opposite, if a function is passed by reference, the value of the parameter is modified in the calling function, and its change affects the actual parameter.

The sample code is as follows:

//5.18.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>using namespacestd;voidSwapint& A,int& B)//This is a reference delivery method{    inttmp; TMP=A; A=b; b=tmp;}voidMain () {intx, y; cout<<"Please enter x"<<Endl; CIN>>x; cout<<"Please enter Y"<<Endl; CIN>>y; cout<<"swapping x and y by reference"<<Endl;    Swap (x, y); cout<<"x="<< x <<Endl; cout<<"y="<< y <<Endl;}//once passed by reference, the original parameters changed.
View Code

Operation Result:

Introduction to C + + Classic-Example 5.18-exchanging values by reference

Related Article

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.