Write a complete C++ program with the two alternate functions specified below, of which each simply triples the variable count defined in main. Then compare and contrast the two approaches. These two functions are; a) Function tripleByValue that passes a copy of count by value triples the copy and returns the new value. b) Function tripleByReference that passes count by reference via a reference parameter and triples the original value of count.
#include <iostream>
using namespace std;
int tripleByValue(int);
void tripleByReference(int &);
int main(){
int count=5;
cout << "Count before call to tripleByValue() is: "<< count;
cout<<"\nCount returned from tripleByValue() is: "<< tripleByValue(count);
cout<< "\nCount after tripleByValue() is: " <<count;
cout<< "\nCount before call to tripleByReference() is: "<< count;
tripleByReference(count);
cout << "\nCount after call to tripleByReference() is: "<< count << endl;
cin>>count;
return 0;
}
//a) Function tripleByValue that passes a copy of count by value triples the copy and returns the new value.
int tripleByValue(int count){
return count *= 3;
}
//b) Function tripleByReference that passes count by reference via a reference parameter and triples the original value of count.
void tripleByReference(int & count){
count *= 3;
}
Comments
Leave a comment