C++ Pass by reference/value.....???

Oct 17, 2011 at 6:58pm
Hi, I have an assignment where I have to have the user input 2 values, x and y, switch the two values, then raise x to the y power. I have to use pass by value in one and pass by reference in another. This is the code I have so far for pass by reference and it works, but I don't know how to use pass by value...

Thanks!

_________________________________________________________________

#include <stdio.h>
#include <iostream.h>
#include <math.h>

void swapnum(int &T, int &S) {
int temp = T;
T = S;
S = temp;


}

int main(void) {

int a, b ;

cout << "This will take your entered values for a and b then switch"
"\n the values and perform A^B.\n"<< endl;
cout << "\n Please enter the value for A \n" << endl;
cin >> a;
cout << "\n Please enter the value for B \n" << endl;
cin >> b;


swapnum(a, b);
cout <<" \n The value for A is now = "<< a <<"\n \n The value for B is now = "
<< b <<endl;

cout << "\n The program will now take A^B and have a value of " << pow (a,b)
<< " \n " <<endl;

system ("pause");

return 0;
}
Last edited on Oct 19, 2011 at 7:24am
Oct 17, 2011 at 7:03pm
your function swapnum returns nothing to the main function. Hence the values in the main function arent interchanged at all...
either use references or COUT inside the swapnum function
Oct 17, 2011 at 10:15pm
@ Julianne: You are passing by reference with the use of the '&' in front of each parameter name.

pass by reference: void swapnum(int &T, int &S) //ok

pass by value: void swapnum(int T, int S) //this would not work


@ network burner: Julianne's already passing by reference... the function should work.
Topic archived. No new replies allowed.