Value-based and reference-based calls in C/C ++

Source: Internet
Author: User

In many programming languages, call-by-value and call-by-reference methods are used to call functions ).

When a parameter is passed by value, a copy of the parameter value is generated and passed to the called function. The change of the copy does not affect the original variable value of the caller. This prevents unexpected side effects from affecting development correctness, reliable system. One disadvantage of calling by value is that if a large data item is passed, copying the data may take a long execution time.

 

By referencing the call, the caller allows the called function to directly access the caller's data and allow the called function to modify the data.

The reference call is advantageous to the performance and eliminates the overhead of assigning a large amount of data.

 

The following is an example of <C ++ University tutorial>:

 

# Include <cstdlib>

# Include <iostream>

 

Using namespace STD;

Int squarebyvalue (INT );
Void squarebyreference (Int &);

Int main (){
Int x = 2, Z = 4;
Cout <"x =" <x <"before squarebyvalue/N"
<"Value returned by squarebyvalue :"
<Squarebyvalue (x) <Endl
<"X =" <x <"after squarebyvalue/N" <Endl;
Cout <"z =" <z <"before squarebyreference" <Endl;
Squarebyreference (z );
Cout <"z =" <z <"after squarebyreference" <Endl;
Return 0;
}

Int squarebyvalue (int ){
Return a * =;
}

Void squarebyreference (Int & CREF ){
Cref * = CREF;
}

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.