(Pass-by-Value vs. Pass-by-Reference) Write a complete C++ program with the two alternate functions specified below, each of which 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 and
b) function tripleByReference that passes count by reference via a reference parameter and triples the original value of count through its alias (i.e., the reference parameter).

```
// Comparing call by value and call by reference.
#include
using namespace std;

int tripleByValue( int ); // function prototype
void tripleByReference( int & ); // function prototype

int main()
{
int count; // local variable for testing

// prompt for count value
cout << "Enter a value for count: ";
cin >> count;

// using call by value
cout << "\nValue of count before call to tripleByValue() is: "
<< count << "\nValue returned from tripleByValue() is: "
<< tripleByValue( count )
<< "\nValue of count (in main) after tripleCallByValue() is: "
<< count;

// using call by reference
cout << "\n\nValue of count before call to tripleByReference() is: "
<< count << endl;

tripleByReference( count );

cout << "Value of count (in main) after call to "
<< "tripleByReference() is: " << count << endl;
} // end main

// tripleByValue uses call-by-value parameter passing to triple the value
int tripleByValue( int value )
{
return value *= 3;
} // end function tripleByValue

// tripleByReference uses call-by-reference parameter passing
// to triple the variable referenced by valueRef
void tripleByReference( int &valueRef )
{
valueRef *= 3;
} // end function tripleByReference
```

Computer Science & Information Technology

You might also like to view...

What is the highest level of the military classification scheme?

A. Secret B. Confidential C. SBU D. Top Secret

Computer Science & Information Technology

Which of the following statements is false?

a) The HasValue property returns true if a nullable-type variable contains a value; otherwise, it returns false. b) The Value property returns the nullable-type variable’s underlying value. c) The null coalescing operator (??) has two operands. If the left operand is not null, the entire ?? expression evaluates to the left operand’s value; otherwise, it evaluates to the right operand’s value. d) All of the above statements are true.

Computer Science & Information Technology