Usually write the program, we may be more or less hazy about some usage, below I have some easy to confuse everyone, or the use of the wrong place to introduce.
First, some points of attention of the function
1. The function return type cannot be an array type or a function type, but can be a pointer to an array or function.
2. If a function is never used, then only the declaration will not be defined.
It is recommended to replace the pointer with a reference-type parameter in 3.c++.
Second, local static objects
Use the static keyword to make the life cycle of a local variable run through the function call and the time thereafter. Objects are initialized only when the program executes the first time the object defines the statement, until the program terminates.
As an example--
size_t Countnum () {static size_t ctr = 0;return ++ctr;} int main () {for (size_t i = 0; I! = ++i) {cout << countnum () << Endl;} return 0;}
The program outputs numbers 1 through 10.
Iii. referencing formal parameters
If you use a parameter that is a value, then it is inefficient to copy an object or container object of a large class, or if a type may not support copying, you can only access the object of that class by referencing the parameter.
When a function does not need to modify the value of a reference parameter, it is better to use a constant reference, for a reason.
First you need to know a convention: In general, the very amount can be converted to constants, and vice versa.
Look at the following example--
int Getwhitespacenum(string &strwords){int i = 0;for (char s:strwords) {if (Isspace (s)) {i++;}} return i;}
This function is used to obtain the number of whitespace characters in a string, and there is no change to the string in the function body.
If the formal parameter is defined as a normal string &, then the parameter can not pass the string literal value, also cannot pass the constant or the constant reference, brings many problems.
But if you write the arguments as constant references, the problems will no longer exist.
Four, function return value
When a value is returned, a copy of the value is returned;
When a reference type is returned, a reference to the object is returned, and no copy occurs.
Note: Do not return a reference or pointer to a local object!
Const string &getname () {string strname;//changes in some way Strnameif (!strname.empty ()) return Strname;elsereturn "NoName";}
After the function ends, the space for the temporary object is freed, so two return statements point to memory space that is no longer available.
Those pits in C + + functions