Use Xcode to write C + + program [4] Functions
This section includes reference functions, inline functions, to prevent modifying function arguments, and the function itself with default values.
Referencing functions: Preventing copying of objects and reducing system overhead
Inline functions: Compile when the code is embedded according to the situation, the compiler will not be successful in the final decision, reduce the system overhead to improve performance
Reference function (prevents tampering with the initial value of the parameter declaration): Prevents the data source from being modified
The function parameter has a default value: A function parameter can be given a default value, and the use of a refinement function
The simplest of functions
#include <iostream>usingnamespace std; int addition (intint b) { return a + b;} int Main () { int z; = Addition (5,3); " " << z << Endl;}
Print results
is 8 0
Pass-through reference (int& representation )
#include <iostream>using namespacestd;voidDuplicate (int& A,int& B,int&c) {a*=2; b*=2; C*=2;}intMain () {intx =1, y =3, z =7; Duplicate (x, y, z); cout<<"x="<< x <<", y="<< y <<", z="<< Z <<Endl; return 0;}
Print results
x=2, y=6, z=0
Prevent tampering with data sources (const-Modified variables)
#include <iostream>#include<string>using namespacestd;stringCONCATENATE (Const string& A,Const string&b) {returnA +b;}intMain () {stringx =" You"; stringy ="xianming"; cout<< concatenate (x, y) <<Endl; return 0;}
Print results
0
inline functions (reduce the cost of function calls)
#include <iostream>#include<string>using namespaceStd;inlinestringCONCATENATE (Const string& A,Const string&b) {returnA +b;}intMain () {stringx =" You"; stringy ="xianming"; cout<< concatenate (x, y) <<Endl; return 0;}
Print results
0
function with default value (if no value is assigned, there is a default value)
#include <iostream>using namespacestd;intDivide (intAintb =2) { intR; R= A/b; return(R);}intMain () {cout<< Divide ( A) <<Endl; cout<< Divide ( -,4) <<Endl; return 0;}
Print results
0
Functions are declared first and then used
#include <iostream>using namespacestd;voidOdd (intx);voidEven (intx);intMain () {inti; Do{cout<<"Please , enter number (0 to exit):"; CIN>>i; Odd (i); } while(i!=0); return 0;}voidOdd (intx) { if((%2)!=0) cout <<"It is odd.\n"; Elseeven (x);}voidEven (intx) { if((%2)==0) cout <<"It is even.\n"; Elseodd (x);}
Recursive invocation
#include <iostream>using namespacestd;LongFactorial (Longa) {if(A >1) return(A * factorial (a)1)); Else return 1;}intMain () {LongNumber =9; cout<< number <<"! = "<<factorial (number); return 0;}
Print results
9 362880 0
[C + +] use Xcode to write C + + program [4] Functions