The difference between passing by reference and passing by value in C and the usage of the ref and out keywords

  • 2020-05-17 06:13:21
  • OfStack


/ to 3 Order the integers from smallest to largest and sum them and their averages 
// Among them, 3 The order result is passed by the reference parameter. Its and are passed by the output parameters; The average is returned by the return value. 
// in Main() Method implementation 3 The input of the desired integer and the output of the result 
// Purpose: to define the method; Call method; Understand the reference-passing relationship between formal parameter and argument; Familiar with the use of reference parameters and output parameters. 
using System;
class Class1
 {
   //x,y,z Is a parameter, 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,total Is a parameter, passed by reference (ref parameter ,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,c It is an argument that will be assigned to the parameter i,j,k,total;
      int a, b, c;
      // The statement out parameter result, You don't have 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);
      //Sort(int x, int y, int z) In the function, formal parameters x,y,z It's passed by value, so even if it's in the function x=x+y+z; function       // The argument after execution a Values are the same. 
      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/"!",a);
      //Average(ref int i, ref int j, ref int k, out int total) In the function, formal parameters a,b,c,result Are all         // Passed by reference, after execution a Values change. 
      Console.WriteLine("The average result is {0}",Average(ref a,ref b,ref c, out result));
      //ref The parameter must be initialized several times before the method is called. 
      // while out Parameters can be uninitialized before calling a method; they are passed by reference 
      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}!",a);
      Console.ReadLine();
    }
 }

Questions and answers:

1. When the value is passed, why does the change of parameter value in the called method not affect the corresponding argument?
Answer: because when passed by value, the system first allocates memory space for the parameter of the method being called, and then copies the value of the argument to the parameter at position 11. The value stored in the parameter is just a copy of the argument, so any change in the parameter value in the called method does not affect the corresponding parameter.

2. What is the difference between value passing and reference passing? What is a value parameter and how is it passed?
Answer: when the value is passed, the system first allocates the memory space for the parameter of the called method, and copies the value of the argument to the parameter according to position 11. After that, any change of parameter value in the called method will not affect the corresponding argument. In reference passing, the system does not copy the value of the argument itself and pass it to the parameter, but passes its reference value (that is, the address value) to the parameter. Therefore, the variable on the address referenced by the parameter is the same as the passed parameter. Any change in the value of the corresponding parameter in the method body will affect the parameter passed as a reference.

3. What are formal parameters and what are real parameters?
A:
Parameters: the parameters specified in the definition function are parameters, which do not occupy the memory storage unit in the absence of function calls, and are allocated to the memory unit only in the case of function calls. At the end of the call, the memory unit occupied by the parameter is also freed.

Arguments: arguments can be constants, variables, and expressions, but they require certain values. Assign the value of the argument to the parameter at call time. In memory, the argument unit and the parameter unit are different units. When the function is called, the parameter is assigned a storage unit and the corresponding value of the argument is passed to the parameter. After the call, the parameter unit is released and the argument unit retains its original value.

To understand:
The argument is what is sent into the method ~~ line argument is a copy of what is sent into the method. After processing, the method returns one thing -- the return value.

When the value is passed, the argument is constant ~ the parameter changes with the calculation ~~
When a pointer/reference is passed, ~~ line arguments change.

The transfer of parameters is divided into: 1. Value mode parameter transfer, 2. Reference mode parameter transfer.
1) pass by value (cannot change argument)
Arguments are variables, expressions, etc.

When a function is called, the arguments and parameters exist in two different regions of memory. The arguments first make a copy of themselves and then pass the copy to the parameters. Since it is passed as a copy, the argument is unaffected by the parameter, and the argument value is not changed.

2) pass by address (you can change the argument)
Arguments are Pointers/references.

When the function is called, the pointer is passed to you, the parameter and argument Pointers are the same, and any operation on the parameter is equal to the operation on the argument. The value of the argument can be changed.

Influence on parameters:
Two data types: value type + reference type
Two methods of parameter transfer: value parameter transfer + reference parameter transfer (ref and out keywords);

The above four kinds of parameter combination in addition to the value parameter transfer method to transfer the value type data, other combination method to the parameter operation will affect the parameter, will change!

Value types: simple types (int float, double, long, char, bool) + + structure
Storage structure: the data is stored in the stack (stack: first in, then out; Single entry, single exit); High efficiency
Assignment: a value is passed

Reference types: all types other than simple types (int,float,double)+ structures + enumerations are reference data types. Such as string; object; Class; The array; Entrust; Interface...
Storage structure: address in stack; Put data in the heap;
Assignment: the address of the data.

Formal parameters: called "formal parameters" are the parameters used to define the name and body of a function and to receive the parameters passed in when the function is called.
Arguments: all called "actual arguments" are passed as arguments to the function when called.

The formal and argument types must be 1 to 1, or must conform to the implicit conversion rule,
When parameter and argument are not pointer types (that is, not passed by reference, but by value),
When the function is running, the parameter and argument are different variables,
They are located in different locations in the memory, shape will be real
The parameter content is copied, and the parameter is released at the end of the function.
The argument content does not change.

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

The biggest use of passing by reference is for "operator" overloading!

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 arguments can be uninitialized before calling the method; they are passed by reference

After C++ has "pass by reference", "change of parameter does not affect argument" is invalidated. Because it's not a value that's passed to the function, it's the variable itself. The parameter defined in a function is still a local variable, but it is a reference. Although the scope of this reference is limited to the inside of the function, because it is the same thing as an argument, the operation on it is exactly the same as the operation on an argument. For example, if you ask "black whirlwind" to buy fish, or "iron ox" to buy fish, the same person will go.

Why is there such a thing as "reference-passing" C++? One is that only references can achieve operator overloading, which we'll talk about later. However, regardless of this, whether the parameter is a reference directly affects the efficiency of program execution. Mentioned earlier, the value of the argument should be used when the function call to initial taxiing, the initialization process includes the definition of a variable, and then give it a value of two process, if the variable is not internal variable, but a class object, then, define a class object can be complex, and initialize the object 1 sample will be very complicated. The reference simply gives the object a single name, does not involve definition or initialization, and does not need to be released out of scope.

In contrast, passing by pointer avoids the definition, initialization, and release of class objects. You only need to pay for the definition, initialization and release of pointer variables. But Pointers are too deadly. Even skilled programmers can't guarantee that there will never be a "wild pointer," and the cost of a wild needle is almost always a program crash.

Citation is not a vegetarian, if the pointer is "to help you with a key to my house", then citation is directly to give you the property of my house. Sometimes we use reference passing just for efficiency, and don't want the argument to be modified, so remember to mark the argument const, such as "UINT GetLength(const CString&)".

By the way, pointer passing can also be done this way. Defining the parameter as a pointer to an const object (rather than an const pointer) reduces lethality and protects the memory for the argument. If it is a normal value transfer, then the presence or absence of const does not affect the outside of the function. However, I personally think that sometimes adding const is also a good thing. If the logic of the program doesn't need to change the parameters, and it actually writes the code by mistake, adding const will allow the compiler to find BUG for us.


Related articles: