Value passing, pointer passing, reference passing (C + + exclusive) Nature

Source: Internet
Author: User

To understand the difference between value passing, pointer passing, and reference passing, the main purpose is to understand the arguments and parameters of the function, the scope of the function (automatic variables, stacks), the layout of the memory, and the characteristics of pointers and references. Here the main summary of the three kinds of parameter transfer method used in the main occasions.

    • Value passing: Only input values are provided to the function, replication overhead is required, and large objects seldom use value delivery.
    • Pointer passing: You can change the value of the pointer to the content, but you cannot change the pointer itself, without duplicating the overhead. If you need to change the pointer itself, you can use a double pointer or a pointer reference.
    • Reference delivery: In addition to providing input values, the result of the operation is returned without duplication overhead.
#include <stdlib.h>

Value passing, the function body variable n is a copy of the parameter n, the function body changes the value of n does not change the outside n
void Addtenbyval (int n)
{
n = n + 10;
Return
}

Pointer passing, n is a pointer to an external variable, changes the value of the *n, and also changes the outside variable's
void addtenbyptr (int *n)
{
*n = *n + 10;
Return
}

Reference passing, alias reference, reaching
void addtenbyref (int &n)
{
n = n + 10;
Return
}

int main (int argc, char *argv[])
{

int n = 10;

printf ("Value before passing, n=%d\n", N);

Value passing
Addtenbyval (n);

printf ("Value passed, n=%d\n", N);

printf ("Pointer before passing, n=%d\n", N);

Pointer passing
Addtenbyptr (&n);

printf ("Pointer passed, n=%d\n", N);

printf ("Before the reference is passed, n=%d\n", N);

Reference delivery
Addtenbyref (n);

printf ("After the reference is passed, n=%d\n", N);

System ("pause");

return 0;
}

Later review of the time and wrote a demo, this does not need to explain, we all understand.

#include <stdio.h>
#include <tchar.h>
#include <cstdlib>
#include <iostream>
#include <sys/timeb.h>
#include <ctime>
#include <climits>

using namespace Std;

Interchange parameters-value passing
void Swapbyval (int v1,int v2)
{
int tmp = v2;
v2 = v1;
V1 = tmp;
}

Interchange Parameters-Reference delivery
void swapbyref (int &v1,int &v2)
{
int tmp = v2;
v2 = v1;
V1 = tmp;
}

Interchange parameters-pointer passing
void swapbyptr (int *v1,int *v2)
{
int tmp = *V2;
*v2 = *V1;
*V1 = tmp;
}

int _tmain (int argc, _tchar* argv[])
{
Value passing
int a = ten, B = 20;
cout << "value before delivery: a =" << a << "; b = "<< b << Endl;
Swapbyval (A, b);
cout << "After value is passed: a =" << a << "; b = "<< b << Endl;

Reset-Reference delivery
A = ten, B = 20;
cout << "Reference before delivery: a =" << a << "; b = "<< b << Endl;
Swapbyref (A, b);
cout << "After the reference is passed: a =" << a << "; b = "<< b << Endl;

Reset-pointer passing
A = ten, B = 20;
cout << "Pointer before pass: a =" << a << "; b = "<< b << Endl;
Swapbyptr (&AMP;A,&AMP;B);
cout << "After the pointer is passed: a =" << a << "; b = "<< b << Endl;

System ("pause");
return 0;
}

Why does C + + introduce reference delivery?

The pointer itself is also a variable, its value is an address, note that this address is the pointer to the address of the variable, not the address of the pointer's own variable, so if the pointer as a function argument, then the formal parameters and arguments are an address, both point to the same variable (the argument pointer to the variable), The value of the pointed variable can be changed by this address, but if you modify the value of the parameter pointer itself, the argument pointer is not modified because the argument pointer and the parameter pointer are two different variables that occupy a different memory location, except that the two variables have the same value (the address of the variable being pointed to) when passed in.
So, if you want to modify a variable, pass the address (pointer) of the variable. If you want to modify a pointer itself, pass the address of the pointer, which is a pointer to a two-level pointer.

Conceptually speaking. A pointer is essentially a variable that holds the address of a variable, logically independent, and can be changed, including the change in the address it points to and the data stored in the   address to which it points. The reference is an alias, it is logically not independent, its existence is dependent, so the reference must be initialized at the outset, and its reference to the object in its entire life week   period can not be changed (from beginning to end can only be attached to the same variable).   in C + +, pointers and references are often used for parameter passing of functions, however, pointer passing parameters and reference passing parameters are inherently different:  pointer passing parameters are essentially the way value is passed, which is passed an address value. In the process of value passing, the formal parameters of the called function are treated as local variables of the modulated function, that is, the memory space is opened in the   stack to hold the value of the arguments put in by the key function, thus becoming a copy of the argument. The characteristic of value passing is that any operation of the modulated function on the formal parameter is   as a local variable, and does not affect the value of the argument variable of the main melody function. (Here is the address value of the argument pointer itself does not change)   while in the reference pass process, the parameters of the called function as local variables in the stack open up memory space, but this is stored by the key function is put in the argument variable of the   address. Any operation of the modulated function on the formal parameter is handled as an indirect addressing, that is, the argument variables in the central Melody function are accessed through the address stored in the stack. Because of this, any action that the modulated function has on the parameter   does affect the argument variables in the keynote function.   Reference passing and pointer passing are different, although they are a local variable on the function stack space, but any handling of reference parameters is handled by an indirection   to the related variable in the key function. For pointers passing parameters, if you change the address of the pointer in the called function, it will not affect the relevant variable of the key function. If you want   to change the related variable in the key function by passing the pointer parameter, you have to use a pointer to the pointer, or a pointer reference.   to further deepen the distinction between pointers and references, let me elaborate on the differences between them from a compilation point of view:  the program adds pointers and references to the symbol table at compile time, and the symbol table records the variable name and the corresponding address of the variable. The corresponding address value of the pointer variable on the symbol table is the address value of the pointer variable  , and the corresponding address value on the symbol table refers to the address value of the Reference object. The symbol table is not changed after it is generated, so the pointer can change the object it points to (the value in the pointer variable   can be changed), and the reference object cannot be modified.   Finally, summarize the same points and different points of pointers and references: & #9733; The same point: & #9679; The concept of an address;  a pointer to a piece of memory whose contents are the address of the referred memory, whereas a reference is an alias for a block of memory.  & #9733 different points: & #9679; The pointer is an entity, and the reference is only an individual name; & #9679; The reference can only be initialized once at the time of the definition, and then immutable; pointer variable; reference "mindedness", Pointers can be "inconstant"; & #9679; references are not const, pointers have const,const pointers immutable; (specifically, there is no int& const A in this form, whereas Const int& A is a     ,   the former guidelines with   itself is the alias can not be changed, which is of course, so do not need this form, the latter refers to the value of the reference can not be changed)  & #9679; The reference cannot be null, the pointer can be empty; & #9679; " The sizeof reference "gets the size of the variable (object) that is pointed to, and the" sizeof pointer "gets the size of the pointer itself; & #9679; the pointer and the reference self-increment (+ +) do not have the same meaning; & #9679; The reference is type-safe, and the pointer is not (reference is more than pointer type checking      one, reference concept   reference introduces a synonym for the object.) Defining a reference is similar to defining a pointer, but using & instead of *. Example: Point pt1 (10,10); Point &pt2=pt1; A reference to PT1 is defined for pt2. With this definition, PT1 and pt2 represent the same object. It is particularly emphasized that a reference does not produce a copy of the object, just a synonym for the object. Therefore, when the following statement executes: Pt1.offset (2,2), pt1 and pt2 all have (12,12) values. A reference must be initialized as soon as it is defined, because it must be a synonym for something. You cannot initialize a reference until you define it first. For example, the following statement is illegal: Point &pt3;pt3=pt1; so since the reference is just a synonym for something, what is the use of it? The following is a discussion of the two main uses of a reference: as a function parameter and return an lvalue from a function.   Second, reference parameter  1, pass variable parameter traditional C, the function is called by the value of the argument is passed, that is, the function's parameters do not have the ability to return a value. So in the traditional C, if the function parameter has the ability to return a value, it is often implemented by pointers. For example, the C program that implements the exchange of two integer variable values is as follows: void swapint (int *a,int *b) {int temp;temp=*a;a=*b;*b=temp;}   After using the reference mechanism, the C + + version of the above program is: void swapint (int &a,int &b) {int temp;temp=a;a=b;b=temp;} The C + + method that calls the function is: Swapint (x, y); C + + automatically passes the address of X, y as an argument to the Swapint function.  2, passing a large object to a function when a large object is passed to a function, a reference parameter can be used to increase the efficiency of the parameter passing, because the reference does not produce a copy of the object,When a parameter is passed, the object does not need to be copied. The following example defines a class for a set of finite integers: const maxcard=100; Class Set{int Elems[maxcard];//The element in the set and, Maxcard represents the maximum number of elements in the collection. int card; The number of elements in the collection. Public:set () {card=0;}//constructor friend set operator * (set, set); Overloaded operation symbol *, used to calculate the intersection of the set with the object as a value parameter//friend Set operator * (Set &, set &) overloaded operation symbol *, used to calculate the intersection of the set with the object reference as a value parameter ...} First consider the implementation of set intersection set operator * (set Set1,set Set2) {set res;for (int i=0;i<set1.card;++i) for (int j=0;j>set2.card;++j) if ( Set1.elems[i]==set2.elems[j]) {res.elems[res.card++]=set1.elems[i];break;} return res;} Because overloaded operators cannot operate on pointers alone, we must declare the operands as set type instead of Set *. The entire collection is duplicated every time the intersection is used, so it is inefficient. We can use references to avoid this situation. Set operator * (set &set1,set &set2) {set res;for (int i=0;i<set1.card;++i) for (int j=0;j>set2.card;++j) if ( Set1.elems[i]==set2.elems[j]) {res.elems[res.card++]=set1.elems[i];break;} return res;}   Reference return value   If a function returns a reference, the call to that function can also be assigned a value. Here is a function that has two reference parameters and returns a reference to a double-precision number: Double &max (double &d1,double &d2) {return d1>d2?d1:d2;} Since the max () function returns a reference to the double precision number, we can use Max () to add 1 to the larger double.: Max (x, y) +=1.0;

Three types of references used in the scene:

Value passing, pointer passing, reference passing (C + + exclusive) Nature

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.