Reviewing C in C++(cont) intⅸ=1024,Y=4096; int &rx= ix into pi= &rX rX=i++ Reference rX could be regarded as an alias or another name of ix Could rX represent iy later?---no pi &iri1//---Only a pointer could do that
Reviewing C in C++ (cont.) int iX = 1024, iY = 4096; int &rX = iX; int* pi = &rX; rX = iY++; ◼ Reference rX could be regarded as an alias or another name of iX ◼ Could rX represent iY later? --- No! ◼ pi = &iY;//---Only a pointer could do that
Reviewing C in C++(cont) int Swap(intⅸ,jntY int Swap(intx pX, int* pY; int Swap(int &iX, int &ir The first two are passing by value, the last is passing by reference The first could not modify the value of arguments outside of Swap while the last two could
Reviewing C in C++ (cont.) int Swap(int iX, int iY); int Swap(int* pX, int* pY); int Swap(int &iX, int &iY); ◼ The first two are passing by value, the last is passing by reference ◼ The first could not modify the value of arguments outside of Swap, while the last two could
Reviewing C in C++(cont) J3 Reasons to use passing by reference o modify the objects that passed in the function To avoid the cost of copying large objects To have more than one return values struct Matrix( double a[ 1000011100001); bool add even(int a, int b, int& int fI(Matrix m) if(a%2=0&&b%2=0 int f2(Matrix& m) a+b: return true return false
Reviewing C in C++ (cont.) ◼ 3 Reasons to use passing by reference: ◼ To modify the objects that passed in the function ◼ To avoid the cost of copying large objects ◼ To have more than one return values struct Matrix { double a[10000][10000] }; int f1(Matrix m); int f2(Matrix& m); bool add_even(int a, int b, int& c) { if (a%2 == 0 && b%2 == 0) { c = a+b; return true; } return false; }
Reviewing C in C++(cont) The inner mechanism of reference and pointer may be similar, but they are quite different in usage a Using Reference when you find It always represents a non-null object And it will not represent any other objects a Using Pointer otherwise Pointer could be re-assigned values, while eference could not
Reviewing C in C++ (cont.) ◼ The inner mechanism of reference and pointer may be similar, but they are quite different in usage ◼ Using Reference when you find ◼ It always represents a non-null object ◼ And it will not represent any other objects ◼ Using Pointer otherwise ◼ Pointer could be re-assigned values, while reference could not