Question

When I ran this the output was:
15
3
21
21

Shouldn't it be:
15
3
21
3

How did it get 21 for the last number? Doesn't num=3?

#include <iostream>
using namespace std;
double test1 (double first, double second);
double test2 (double first, double &second);

void main()
{
double num = 3;
cout<< test1 (5, num) <<endl;
cout << num << endl;
cout<< test2 (7, num) << endl;
cout<< num <<endl;
}

double test1 (double first, double second)
{
second = first * second;
return second;
}

double test2 (double first, double &second)
{
second = first * second;
return second;
}
num is passed by reference (the '&' symbol) in your test2 function.
This means that whatever changes are made to it inside the function
will remain after the function returns.

More info here -> http://cplusplus.com/doc/tutorial/functions2/
in your test2 function you are passing num by reference which means your function will now directly modify num. In test1 you are passing num by value so a copy of num is made which means the original num in your main function doesn't get touched.
Ah, that was stupid of me. I didn't read it carefully. Thanks for the replies!
Topic archived. No new replies allowed.