parameter defaults and references in C + +

Source: Internet
Author: User

This article will collate some knowledge about parameter defaults and references.

(a) parameter default : The parameter default includes full default and semi-default. As the name implies, all the defaults are the default values for all parameters of the function, and the semi-default is that only some of the parameters of the function give the default values . Look at the code below:

#include <iostream> using namespace std;  int Add (int x, int y) {return x + y;      } int main () {int ret = ADD ();      System ("pause");  return 0; }

If you write the above piece of code, the lower version of VS will not compile, the error is that the Add function does not receive 0 parameters, high version vs will have a red callout. If you do not want to give arguments to the function call, we can use the default parameters, if the Add function is written like this:

int Add (int x = 0, int y = 0) {return x + y; }

This is called the full default. What about the half-default?? To continue the instance:

int Add (int x, int y = 0) {return x + y;      } int main () {int ret = ADD (10);      System ("pause");  return 0; }

This way, the end will be 10 and 0 added. Of course, when called, we can also give two parameters. If we give x the default, y is not the default, see Can not??

int Add (int x = 0, int y) {return x + y; }

If the Add function is written above, the high version vs compiler will error The Red line: The default parameter is not at the end of the parameter list. Think about what this is about? In fact, think about it to understand that when the call (of course, only one of the arguments) will give the arguments given to the function parameter list of the first parameter, it must be wrong. If a more professional explanation, I think: the function parameter into the stack when the argument into the stack frame of the Add function, directly as the first parameter, so ~ summary: using the semi-default, the default parameter can only be in the last side of the parameter list. use of default parameters: If you want to pass the gender parameter to the function, we also agree to the default is male, so, only need to pass the sex is female, give the parameters. This is the purpose of the default parameter.

(ii) References

A reference is an alias for a variable. Like what:

int a = 10; int &ra = A;//ra is the alias of a, int &refa = A;//refa is also an alias of a

Summarize:

    1. A variable can have multiple aliases.

    2. A reference must be initialized when it is defined (indicating which variable is the alias of the defined reference).

    3. References can only be referenced once at initialization time.

Since it is said that a variable can have more than one alias, change the value of the alias, it will change the value of the variable, is not feeling the reference is not safe?? In fact, if you do not want to change, you can use the const modifier.

int a= 10;  const int &RA = A; RA = 20;//Error!

With respect to const, a const-modified variable in C is a constant variable, both a constant and a property of a variable. In C + +, a const-modified variable is a constant. Cannot be modified. When learning pointers, we can use the const modifier if the function of a function is simply to print or if a parameter cannot be changed. The same is true when using references. Example:

void print_a (const int &ra) {RA = 20;//error (left value must be modifiable) cout << ra << Endl;      } int main () {int a = 10;      int &ra = A;      Print_a (a);      System ("pause");  return 0; }

In CPP, if the const is decorated with a local variable, the local variable is in the stack. Is not modifiable, you can use the pointer to modify it. If the const modifier is a global variable, it will not be allocated space when not in use (&n is wrong), only the address when used.

const int n = 10;      int main () {int a = 10;      int &ra = A;      int Arr[n] = {0};//Here is not the use of N, at this time the n is still quite macro identifier const int *P = &n;//n has space, and is read-only, non-modifiable.      System ("pause");  return 0; }

About the correct use of const references: Look at the following sections of code:

const int n = 10; int &REFA = n;

At this point the Refa can be changed, and the value of n can be changed. That's not right. (n is not allowed to change). Make n from security to unsafe.

int m = 10; const int &REFM = m;

That's the right thing to do. Makes M never safe.

const int &refd= 5;

This is the right one. The const-decorated REFD is a reference to a constant.

Double d = 6.15; int &refd = D;

This is not right. If that's the case:

Double d = 6.15; const int &REFD = D;

Why?? Because the type of the reference is int, the type of the variable is double, so a temporary variable (also an implicit type conversion of D) is created with a double type D, and REFD refers to a temporary variable. The exact word is the temporary constant. At this time REFD =D,REFD and D are not in a space. Reference as a function parameter: it is necessary to declare that the underlying reference is still a pointer (this can be observed through assembly code). Let's test the citation and efficiency issues:

#include <iostream>   #include <windows.h>  using namespace std;   struct BigData  {      int arr[100];  };   int getdata (BIGDATA&NBSP;BD)   {      return  Bd.arr[0];  }  int main ()   {      bigdata  bd = { 0 };      int i = 0;       int start = gettickcount ();       for   (i = 0;i < 100000000;i++)       {           getdata (BD);      }       int end = gettickcount ();      cout < < end - start&Nbsp;<< endl;      system ("pause");       return 0;  }

The result of the code test is about 6000 milliseconds. Note: The result of each run is not the same as the state of this CPU. When you change the top code to a reference: efficiency can be increased by about half, you can try. Reference as the return value of the function: Look at the code:

int& Fun () {int num = 10;  return num;      } int main () {int &ret = fun ();      cout << ret << Endl;      System ("pause");  return 0; }

The above code does output 10. But if the above code is to be modified:

int& Fun () {int num = 10;  return num;          } int main () {int &ret = fun ();      printf ("Hello Mr. Yang");      cout << ret << Endl;      System ("pause");  return 0; }

Look at the top of the code, in the higher version of VS output: Mr. Yang Hello. 10 The value of RET will be changed in the low version environment. Because RET receives a local variable num, both occupy the same space when Num disappears, ret disappears and becomes a random value. High version vs (for example vs2015) Why RET's value has been 10, do not know what optimizations were made. 650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/> If the upper code is modified:

int& fun ()   {      int  num = 10;      return num;  }  int  main ()   {            int ret  = fun ();       printf ("Hello Mr. Yang");       Cout << ret << endl;      system ("pause");       return 0;  } 

The value of this RET does not change. Look at the principle: the latter RET is not a reference, save only the value of NUM, so will not disappear with Num disappeared. When referencing is the return value of a function, sometimes it improves efficiency, and sometimes it does not ~ ~ We know that when the return value of a function, int or double, and so on, the return value is brought back with a register. The largest register, however, is 32 bits, and if we are going to return a larger struct, a reference is used, the reference does not create a temporary variable, and the value that needs to be brought back is assigned to the variable that receives the return value. Summary: Using a reference to return with a function that returns a value that is not a built-in type is more efficient (fewer temporary objects are created). When a built-in type is returned, the register is brought back with the same efficiency as using the reference return. The difference between a reference and a pointer: 1. Pointers can be uninitialized when defined, but not referenced. 2. A reference can reference only one variable, whereas a generic pointer variable is not (except for a const-decorated pointer) 3. The size of the pointer is only related to the product table, and the reference size is related to the type of object being referenced. 4. The pointer is from overtime so that the pointer points to the next space that is currently pointing to the space; referencing from overtime causes itself and the value of the object it references to be added 1.5. References are more secure than pointers. (When using pointers, be sure to check if the value of the pointer is null)


parameter defaults and references in C + +

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.