# C # differences between passing by reference and passing by value, and usage of the ref and out keywords

Source: Internet
Author: User

The following describes the differences between pass by reference and pass by value in C # and the usage of the ref and out keywords. For more information, seeCopy codeThe Code is as follows:
/Sort and sum the three integers in ascending order and their average values.
// The values of the three Integers to be evaluated and sorted are transmitted by the reference parameter, the sum is transmitted by the output parameter, and the average value is returned by the return value.
// Implement the input and result output of three integers in the Main () method
// Purpose: Define a method, call a method, understand the reference transfer relationship between the form parameter and the real parameter, and be familiar with the use of reference parameters and output parameters.
Using System;
Class Class1
{
// X, y, and z are parameters passed by value
Static void Sort (int x, int y, int z)
{
Int temp = 0;
If (x> y)
{
Temp = x;
X = y;
Y = temp;
}
If (y> z)
{
Temp = z;
Z = y;
If (x> temp)
{
Y = x;
X = temp;
}
Else
{
Y = temp;
}
}
Console. WriteLine ("The sorted list is {0}, {1}, {2}", x, y, z );
X = x + y + z;
}

// I, j, k, and total are parameters passed by reference (ref and out parameters are passed by reference)
Static double Average (ref int I, ref int j, ref int k, out int total)
{
Double l = 0;
Total = I + j + k;
I = total;
L = (double) (total/3.0 );
Return l;
}

Static void Main ()
{
// A, B, and c are real parameters, which will be assigned to the I, j, k, and total parameters;
Int a, B, c;

// Declare the out parameter result. You do not need to initialize it.
Int result;

Console. Write ("Please enter the first number a = ");
A = Convert. ToInt32 (Console. ReadLine ());
Console. Write ("Please enter the second number B = ");
B = Convert. ToInt32 (Console. ReadLine ());
Console. Write ("Please enter the third number c = ");
C = Convert. ToInt32 (Console. ReadLine ());

Sort (a, B, c );

// In the Sort (int x, int y, int z) function, the form parameters x, y, and z are passed by value, so even if the function contains x = x + y + z; the value of real parameter a remains unchanged after the function // is executed.
Console. writeLine ("The original value of/" a/"is {0}, it hadn't been changed in spite" + "of manipulating the Sort () method, because it is transmitted by a Value para/"x /"! ", );

// In the Average (ref int I, ref int j, ref int k, out int total) function, the parameters a, B, c, and result are all passed by reference, the value of real parameter a changes after execution.
Console. WriteLine ("The average result is {0}", Average (ref a, ref B, ref c, out result ));
// The ref parameter must be initialized several times before calling the method.
// The out parameters can be not initialized before the method is called. They are all passed in reference transmission mode.

Console. writeLine ("The value of/" a/"has been changed due to the Average () method" + "is manipulated, and it is transmitted by a ref para/"ref I /"! Now it is {0 }! ", );

}
}

1. Why does the change of the parameter value in the called method affect the real parameter when the value is passed?
A:When passing by value, the system first allocates memory space for the called method parameters, and then copies the values in the real parameters to the parameters one by one. The value stored in the parameter is only a copy of the real parameter. Therefore, any change in the parameter value in the called method will not affect the corresponding parameter.

2. What is the difference between value passing and reference passing? What is a value parameter and how it is passed?
A:When a value is transferred, the system first allocates memory space for the called method parameters, and copies the values of real parameters to the parameters one by one based on their locations. After that, the parameter value in the called method does not affect the corresponding real parameter. When the reference is passed, the system does not copy the value of the real parameter and then pass it to the actual parameter, instead, the referenced value (that is, the address value) is passed to the form parameter. Therefore, the variables on the address referenced by the form parameter are the same as the passed real parameters, any change to the parameter value in the body of the square method will affect the real parameter passed as a reference.

3. What is a form parameter and a real parameter?
A:
Parameters:
The parameters specified in the definition function are the form parameters. They do not occupy memory storage units when no function call occurs. Only when a function call occurs, the parameters in the function are allocated memory units. After the call is completed, the memory units occupied by the parameters are also released.

Real parameters:Real parameters can be constants, variables, and expressions, but certain values are required. Assign the value of the real parameter to the parameter during the call. In the memory, parameters and parameters are different. When a function is called, a storage unit is assigned to the parameter and the value corresponding to the real parameter is passed to the parameter. After the call is completed, the unit is released and the original value is retained.

Understanding:
The real parameter is something in the method ~~ The row parameter is used to copy and process the provided items in the method. After the processing, the method returns the return value.

When the value is passed, the real parameter is not changed ~ Parameters change with calculation ~~
Pointer/reference transfer time ~~ How can I change the row parameter ~ How to change the real parameter ....

Parameter transmission is divided into: 1. Value-based parameter transmission; 2. Reference-based parameter transmission.
1) pass by value (real parameters cannot be changed)
Real parameters are variables, expressions, and other numerical values.

When a function is called, the real parameters and the form parameters exist in two different regions in the memory. The real parameters are copied by themselves, and then copied to the form parameters. Because a copy is passed, the real parameter is not affected and the real parameter value is not changed.

2) pass by address (real parameters can be changed)
The real parameter is a pointer/reference.

When a function is called, the pointer is passed to you, and the form parameter and the real parameter pointer are the same. Any operation on the form parameter is equivalent to the operation on the real parameter. The value of the real parameter can be changed.

Impact on parameters:
Two data types: Value Type + reference type
Two parameter passing Methods: Value passing parameter + reference passing parameter (ref and out keywords );

The combination of the above four parameters transfers value type data in addition to the value passing parameter method. Other combinations affect parameter operations and change parameters!

Value Type:Simple Type (int, float, double, long, char, bool) + structure + Enumeration
Storage Structure:Data is stored in the stack (Stack: advanced post-release; single portal, single exit); High Efficiency
Assignment Method:The value is passed.

Reference Type:All types except simple types (int, float, double), structure, and enumeration are referenced data types. Such as string; object; Class; array; delegate; interface...
Storage Structure:Stack storage address; stack data storage;
Assignment Method:It is the data address.

Parameters:The parameter "formal parameter" is used when defining the function name and function body. It is used to receive parameters passed in when the function is called.
Real parameters:It is called "actual parameter". It is the parameter that passes the function during the call.

The type of the form parameter and the real parameter must be the same, or the implicit conversion rule must be met,
When the form parameter and real parameter are not pointer types (that is, they are passed by reference rather than by value ),
When the function is running, the form parameter and the real parameter are different variables,
They are located in different locations in the memory.
Copy the content of the parameter and release the parameter at the end of the function,
The real parameter content will not change.

If the function parameter is a pointer type variable (passed by reference ),
The address passed to the function is the real parameter address, which is also used inside the function body
The real parameter address, that is, the real parameter itself.
You can change the value of a real parameter.

The biggest purpose of transferring by reference is to implement "operator" overload!

The difference between the ref parameter and the out parameter is that the ref parameter must be initialized several times before the method is called. The out parameters can be not initialized before the method is called. They are all passed in reference transmission mode.

After C ++ has "reference transfer", "the change of the form parameter does not affect the real parameter" is invalidated. Because it is not a value but a variable itself that is passed to the function. Although the parameter defined in the function is partially variable, it is a reference. Although the scope of this reference is limited to the function, because it is the same as the real parameter, its operation is equivalent to the operation of the real parameter. For example, if you ask "Black tornado" to buy fish, or "Tie niu" to buy fish, they all go to the same person.

Why does C ++ require "reference transfer? One way is that only references can achieve the purpose of overloading operators. Let's talk about this later. However, whether the parameter is referenced directly affects the execution efficiency of the program. As mentioned above, the parameter must be initialized using the value of the real parameter during function calling. the initialization process includes defining a variable and then assigning a value to it, if this variable is not an internal variable but a class object, it may be complicated to define a class object, and initialization of this object is also complicated. The reference only gives the object an alias, does not involve definition and initialization, and does not need to be released when it leaves the scope.

In contrast, pointer transmission can avoid class object definition, initialization, and release. Only the definition, initialization, and release of pointer variables are required. However, the pointer is too lethal. Even skilled programmers cannot guarantee that "wild pointers" will never appear. The cost of wild needles is almost the same as program crash.

References are not vegetarian. If the pointer transmission is "providing you with a key to my house", then the reference transmission directly gives you all the property of my house. Sometimes, we use reference to pass only for efficiency without modifying the real parameter. Remember to mark the form parameter as const, for example, "UINT GetLength (const CString &)".

By the way, pointer passing can also be done. Defining a parameter as a pointer to a const object (instead of a const pointer) can reduce the damage and protect the memory corresponding to the real parameter. If it is a normal value transfer, there is no const that does not affect the external function. However, I personally think that adding const is also a good thing. If the program logic does not need to change the parameters, but the code is written by mistake, and the const can help the compiler find bugs.

Related Keywords:
Related Article

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.