当前位置:网站首页>Function (basic: parameter, return value)

Function (basic: parameter, return value)

2022-07-05 04:18:00 Cao Lele loves learning

Function parameter passing :

A- The value transfer of a function :

void fun(int a,int b);// Function declaration ( The function prototype )

Is to assign an argument to a formal parameter , In function processing , Arguments themselves are unaffected . example :

Realize two data exchanges :

void swap(int ,int );

void swap(int num1,int num2)
{
        int n1,n2,t;

        t =n1;
        n1 = n2;
        n2 = t;
}

reason : Actual parameters a,b Pass it to the formal parameter n1,n2 Only numerical value , and ,a And n1 It's not the same address space at all , So no matter n1,n2 How to operate , Not at all a,b It won't make any impact .

If we want to solve this problem ,2 Ways of planting :

1、 Use global variables —— Don't suggest , Because functions should be modularized as much as possible , Minimize the interaction between data .( So-called : High cohesion , Low coupling ?)

2、 Address delivery ( Pointer passing )—— Suggest

Just say 2、 Address delivery :

B- Function address passing :

  Since then , Put... Directly a,b Pass in your address , To operate ; It's essentially right a,b Operate on your own ( It seems to be bullshit ).

additional :( For safety's sake , Sometimes , We send the address , Nor is it to modify the original data , Then you can use const Decorate it , read-only )

For example, find the string length :

  The return value of the function

Pictured above , After finding the length of the string in the function , I also need to calculate the value , Pass it to the main function to use . The two methods :

1、 Use global variables —— Don't suggest

2、 Use function to return value

The return value of the function

  But be careful :

I just added , Print the returned n Value , Just report a mistake ?

  This is because : Function if you use auto Storage type ( Do not write by default ), The life cycle only exists during the function being called ( Local variables are put on the stack ), After function execution , Will release , Can no longer be visited , If reading and writing , It's illegal .

and return n after , It's OK to assign a function directly to a variable , Because :return Value , Is the return value of the function itself .

If you want to print out n Value , Or above 1 The method described : take n Set to global variable —— Don't suggest .

原网站

版权声明
本文为[Cao Lele loves learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050416449729.html