Simple analysis of function parameter transfer in c and c++

  • 2020-04-02 01:11:44
  • OfStack

Let's take a look at a piece of code to see the results of the three passes.


#include <cstdlib>
#include <iostream>
using namespace std;
void change1(int n)
{
     cout << " Value passed -- Function operation address " << &n << endl;
     n ++;
}
void change2(int &n)
{
     cout << " reference -- Function operation address :" << &n << endl;
     n ++;
}
void change3(int *n)
{
     cout << " Pointer passed -- Function operation address " << n << endl;
     *n = *n + 1;
}
int main(int argc)
{
    int n = 10;
    cout << " Arguments to address :" << &n << endl;
    cout << " The original cost  n =" << n << endl;
    change1(n);
    cout << "afterchange1 n =" << n << endl;
    change2(n);
    cout << "afterchange2 n =" << n << endl;
    change3(&n);
    cout << "afterchange3 n =" << n << endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

The print result is as follows:
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201307/20130724100955.png ">

It can be seen that the change1 function did not change the value of the original argument n of 10, while the change2 and change3 functions successfully changed its value.
Also, if you look at the operational address of the function, you will see that the operational address of change1 is not the address of argument n.
Description:
1. The form of value transfer does not pass n itself, so the value of n cannot be changed.
2. Reference passing, pointer passing, in fact, is to pass in the address, can successfully operate on the address.
But beware:
1. References and Pointers need to be initialized before passing.
2. References and Pointers in memory to open up the storage unit should be legal units, should not be NULL.
3. Once the reference is initialized, the relationship of the reference cannot be changed, and the pointer can change the object at will.
For the case where there is no initialization pointer or reference, let's look at another example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
void init(char *p)
{
    p = (char *)malloc(100);
    cout << " Pointer passed -- Function operation address " << p << endl;
}

int main()
{
    char *p = NULL;
    cout << " Argument original address " << p  << endl;
    init(p);    

    if(p)
    {
        strcpy(p, "hello"); 
        printf("%s n", p);
    }
    else
    {
        printf("%s", "p not init n");
    }
    free(p);
    system("PAUSE");
    return EXIT_SUCCESS;
}

Output results:
< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201307/20130724101017.png ">


Related articles: