An arguement corresponding to a(n) ____________ parameter cannot be changed by a function call.
a) call-by-reference
b) call-by-value
c) object
d) class
// Example program
#include <iostream>
#include <string>
int passValue( int stuff );
int passRef( int &stuff );
int main()
{
int a = 5;
int b = 10;
std::cout << "Original values of a and b are " << a << ", " << b << std::endl;
passValue(a);
std::cout << "New value of a is " << a << std::endl;
passRef(b);
std::cout << "New value of b is " << b << std::endl;
}
int passValue( int stuff )
{
stuff += 5;
return stuff;
}
int passRef( int &stuff )
{
stuff *= 2;
return stuff;
}
Correct. Basically the difference between passing by value and passing by reference is this:
In passing by value, you're creating another copy of the variable to be changed. Think of two hamster cages connected by one tube. Box A on the left (if you can picture it in your mind) is the function definition. Box B on the right is the call to the function in main(). When you pass by value, you create another hamster. So Box A has one hamster that does its thing, and Box B has another that's the exact same thing.
In passing by reference, imagine the same two hamster cages, and still the one hamster in Box A. When a passing by reference function gets called, the one hamster in Box A runs straight through the tube to Box B and because of that, it's tired. So instead of an ok hamster in Box A, you now have a tired hamster in Box B. How many hamsters do you got? Still one.
int addtwoNumbers(int a, int b)
{
// No time, just for testing other parts, low priority, do later = no guts
return 6;// whatever, just enough so it works
}