|
I said hopefully, because CS170/CS171 uses Java and:
|
Anyway, I like to show you the effect of these dufferent ways to pass parameters in C++
|
#include <iostream>
using namespace std;
/* ====================================================
Function with a parameter that is passed by value
==================================================== */
void f(int a) // Var a is passed by value
{
a = a + 1;
}
int main(int argc, char *argv[])
{
int k = 7;
cout << "before f( ): " << k << endl; // Prints: 7
f(k);
cout << "after f( ): " << k << endl; // Prints: 7 (k unchanged !)
}
|
In this program, the function f(a) updates the parameter variable a.
Due to the fact that the parameter a is passed-by-value, the effect of this update will be:
|
How to run the program:
|
|
#include <iostream>
using namespace std;
/* ====================================================
Function with a parameter that is passed by value
==================================================== */
void f(int & a) // Var a is passed by reference
{
a = a + 1;
}
int main(int argc, char *argv[])
{
int k = 7;
cout << "before f( ): " << k << endl; // Prints: 7
f(k);
cout << "after f( ): " << k << endl; // Prints: 8 (k changed !)
}
|
In this program, the function f(a) updates the parameter variable a.
Due to the fact that the parameter a is passed-by-reference, the effect of this update will be:
|
How to run the program:
|