C ++ Primer study note _ 21 _ Function

Source: Internet
Author: User

Function-Function Definition and parameter transfer



I. Function Definition
int gcd(int v1,int v2){    while (v2)    {        int temp = v2;        v2 = v1 % v2;        v1 = temp;    }    return v1;}

1. function calls do two things:

1) initialize the parameter of the function with the corresponding real Parameter

2) transfer control to the called function. At this time, the main function is suspended and the called function starts execution.


2. A function cannot return another function or a built-in array type, but can return a pointer to a function or to an array element:

int *foo_bar(){    //...}

The function returns an int pointer that can point to an element in the array.


Ii. parameter transfer

Every time a function is called, all the parameters of the function are re-created. The passed parameters will initialize the corresponding parameters. If the parameter has a non-reference type, copy the value of the real parameter. If the parameter is of the reference type, it is only the alias of the real parameter.


1. pointer Parameters

// Compare the following two programs void mySwap1 (int * a, int * B) {int temp = * a; * a = * B; * B = temp ;} void mySwap2 (int * a, int * B) {int I = 10; int j = 20; a = & j; B = & I ;}

If the function parameter is a pointerCopyReal parameter pointer. Like other non-reference parameters,Any changes to this type of parameter only apply to local copies.If the function assigns the new pointer to the form parameter, the value of the real parameter pointer used by the main function does not change.


2. const Parameters

Although the function's form parameter is const, the compiler regards the fcn definition as its form parameter declared as a common int type:

void fcn(const int i){    /* fcn can read but not write to i */}void fcn(int i){    /* ... */}// error: redefines fcn(int)

3. Limitations of copying real parameters:

1) when you need to modify the value of the real parameter in the function

2) When a large object needs to be passed as a real Parameter

3) if there is no way to copy an object, such as this object cannot be copied...

// P201 exercise 7.5int get_Bigger (int x, const int * y) {return (x> * y? X: * y );}

4. Reference parameters

vector<int>::const_iteratorfind_val(vector<int>::const_iterator beg,         vector<int>::const_iterator end,         int val,         vector<int>::size_type &occur){    vector<int>::const_iterator res = end;    occur = 0;    for (; beg != end; ++beg)    {        if (*beg == val)        {            if (res == end)            {                res = beg;            }            ++ occur;        }    }    return res;}

5. Use const reference to avoid Replication

If the only purpose of using the reference parameter is to avoid copying the real parameter, you should define the reference as const.


6. Restrictions on non-const reference parameters: when calling such a function, it is not allowed to pass a right value or an object of the type to be converted. For example:

int incr(int &val){    return ++val;}int main(){    short val = 0;    val = incr(val);    //error    const int ival = 1;    val = incr(ival);   //error    val = incr(0);      //error    int v3 = 1;    v3 = incr(v3);      //ok}


Reference parameters that do not need to be modified should be defined as const references. Common Non-const reference parameters are not flexible when used:

1) such parameters cannot be initialized using a const object.

2) The real parameter initialization cannot be performed with the literal value or the expression that generates the right value...


7. Pass the reference pointing to the pointer

    int *&v;

From right to left: v1 is a reference associated with the pointer to an int object.

// Understand the following program void ptrSwap (const int * & v1, const int * & v2) {const int * temp = v1; v1 = v2; v2 = temp ;} int main () {int I = 10; const int * pi = & I; int j = 20; const int * pj = & j; cout <* pi <"" <* pj <endl; ptrSwap (pi, pj ); cout <* pi <"" <* pj <endl;} // exchanges the address saved by the pointer, that is, the pointer value is exchanged!

8. vector and other container-type parameters

C ++ programmers tend to pass containers by passing the iterator pointing to elements in the container to be processed:

void print(vector<int>::iterator beg,           vector<int>::iterator end){    while (beg != end)    {        cout << *beg++;        if (beg != end)        {            cout << ' ';        }    }    cout << endl;}

9. The length of an array parameter may cause misunderstanding because the compiler ignores the length specified by any array parameter:

void printValues(const int ia[10]){for (size_t i = 0; i != 10; ++i){cout << ia[i] << endl;}}

The following calls are legal [However, they are incorrect !] :

int main(){int i = 0,j[2] = {0,1};printValues(&i);printValues(j);   return 0;}

Therefore, it may cause out-of-bounds access to the Array Memory. Program execution may produce incorrect output or crash!


10. Pass an array through reference

If the parameter is an array reference, the compiler will not convert the array argument to a pointer, but pass the array reference itself. In this case, the array size will become part of the form parameter and actual parameter type!

void printValues(const int (&arr)[10]){//...}int main(){int i = 0,j[2] = {0,1};int arr[10] = {0};printValues(&i);//errorprintValues(j);//errorprintValues(arr);//error    return 0;}

11. Multi-dimensional array Transfer

The element of a multi-dimensional array itself is an array. The length of all arrays except the first dimension is part of the element type and must be explicitly specified:

void printValues(int (*matrix)[10],int rowSize);

[Note: The following two statements are different]

Int * matrix [10]; // pointer array, which contains an array of 10 pointers, int (* matrix) [10]; // array pointer, A pointer pointing to an array containing 10 elements

12. Three common programming techniques to ensure that arrays are not accessed across borders

1) place a flag in the array to check the end of the array, such as '\ 0' of the C-style string'

2) use the standard Library Specification: Pass the pointer to the next position of the first and last elements of the array

void printValues(const int *beg,const int *end){while (beg != end){cout << *beg++ << endl;}}int main(){int j[2] = {0,1};printValues(j,j+2);}

3) explicitly passing parameters of array size

void printValues(const int *arr,size_t size){for (size_t i = 0; i != size; ++i){cout << arr[i] << endl;}}int main(){int j[2] = {0,1};printValues(j,sizeof(j)/sizeof(*j));}

// P210 exercise 7.13int sumArr1 (const int * arr) {int sum = 0; for (int I = 0; arr [I]! = 2147483647; ++ I) {sum + = arr [I];} return sum;} int sumArr2 (const int * beg, const int * end) {int sum = 0; while (beg! = End) {sum + = * beg ++;} return sum;} int sumArr3 (const int * arr, size_t size) {int sum = 0; for (size_t I = 0; I! = Size; ++ I) {sum + = arr [I];} return sum;} int main () {int arr1 [11] = {0, 1, 2, 3, 4, 5, 2147483647,}; int arr2 [10] = {,}; cout <sumArr1 (arr1) <endl; cout <sumArr2 (arr2, arr2 + 10) <endl; cout <sumArr3 (arr2, sizeof (arr2)/sizeof (* arr2) <endl ;}

// Exercise 7.14 double sumVector (vector <double >:: const_iterator beg, vector <double >:: const_iterator end) {double res = 0; while (beg! = End) {res + = * beg ++;} return res;} int main () {vector <double> dvec; for (int I = 0; I! = 10; ++ I) {dvec. push_back (static_cast <double> (I);} cout <sumVector (dvec. begin (), dvec. end () <endl ;}

13. main: process command line options

// P211 exercise 7.15int main (int argc, char ** argv) {if (argc! = 3) {cout <"Please use. out I j "<endl; return 0;} cout <atoi (argv [1]) + atoi (argv [2]) <endl ;}

// Exercise 7.16int main (int argc, char ** argv) {for (int I = 1; I! = Argc; ++ I) {cout <* (argv + I) <endl ;}}

14. When you cannot list the types and numbers of all real parameters passed to the function, you can use the omitted parameter.

void printArgv(char **argv,int count,...){    for (int i = 0; i != count; ++i)    {        cout << *(argv + i) << endl;    }}int main(int argc,char **argv){printArgv(argv,argc);}

In the C ++ program, you can only pass the simple array structure type to a function that contains the omitted object parameters. In fact, when you need to pass the omitted object parameters, most class type objects cannot be correctly assigned values!

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.