Pass by Reference
Pass by Reference
Slide2Review on Pass by Value:#include<iostream>using namespace std;void Increment(int Number)(Number =Number+l;cout << "The parameter Number: "<< Number << endl;void main()(int I = 10;Increment(I);//parameter is a variablecout << "The variable I is: "<< I << endl;Note:replacing'byNumber'in the maindoes notchangeanything
Slide 2 Review on Pass by Value: #include <iostream> using namespace std; void Increment(int Number){ Number = Number + 1; cout << "The parameter Number: " << Number << endl; } void main(){ int I = 10; Increment(I); // parameter is a variable cout << "The variable I is: " << I << endl; } Note: replacing ‘I’ by ‘Number’ in the main does not change anything
Slide3Pass by Reference: Example lTo showhowthefunctionaffectsavariable whichis used as a parameter:#include <iostream>using namespace std;void Increment(int& Number)(Number =Number+l;cout << "The parameter Number: " << Number << endl;void main()(int I=10;Increment(I);//parameter is a variablecout << "The variable I is: "<< I << endl;
Slide 3 Pass by Reference: Example 1 To show how the function affects a variable which is used as a parameter: #include <iostream> using namespace std; void Increment(int& Number){ Number = Number + 1; cout << "The parameter Number: " << Number << endl; } void main(){ int I = 10; Increment(I); // parameter is a variable cout << "The variable I is: " << I << endl; }
Slide4Passing Parameters by ReferenceSdnduFunctionTo have a functionwithmultiple outputs,we have to usepass by reference.Efficiencyforlargeobjects!Reference(address)of parameter is passed to thefunctioninstead of its value.Ifthe function changes the parameter value, the changeswill bereflected inthe program calling it
Slide 4 Passing Parameters by Reference To have a function with multiple outputs, we have to use pass by reference. Efficiency for large objects! Reference (address) of parameter is passed to the function, instead of its value. If the function changes the parameter value, the changes will be reflected in the program calling it
Slide5Specify the passing of a parameter byreference:T&<type>&<variable>,.int&x,double&y,char&zThenotationT&meansa referencetoTVeryinteresting'notation we will continue to see it later on..“reference'does notexist inC,ramificationof low-level pointer.Areferenceisanalternativenameforanobject.inty=10;int&x=y;llxandyrefertothesameint
Slide 5 <type>& <variable>, . int& x, double& y, char& z The notation T& means a reference to T Specify the passing of a parameter by reference: T& Very ‘interesting’ notation we will continue to see it later on . ‘reference’ does not exist in C, ramification of low-level pointer. int y=10; int& x = y; // x and y refer to the same int A reference is an alternative name for an object