Call-By-Reference and Value Function

Hello, I'm having a problem solving the following to make it "correct". Any guidance is greatly appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace	std;
int fun1(int x)
{
fun2(x);
}
void fun2(int& y)
{
y=3*y;
return y;
}
int main()
{
int x=2;
cout << fun1(x) <<endl;
cout << fun2(x) <<endl;
}


The issues that I've found so far are, or what I think they are:
A) y=3*y; but y has no value other than y=3*y so maybe y=3*x;?



nm
Last edited on
closed account (zb0S216C)
"::fun2( )" cannot cannot return a value. You can either swap the return type from "void" to "int" or remove the "retrun" statement altogether.

Wazzak
Last edited on
Got ya, because void cannot return a value, return can only be used to cease the execution of any further pieces of code if something is met.

However, this is what I have now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int fun1(int x)
{
   fun2(int x);
}
int fun2(int& y)
{
   y=3*y;
   return y;
}
int main()
{
   int x=2;
   cout << fun1(x) << endl;
   cout << fun2(x) << endl;
}


With two errors:

1
2
3
4
5
[****@storm homework]$ g++ prob4.cpp
prob4.cpp: In function ‘int fun1(int)’:
prob4.cpp:6:7: error: expected primary-expression before ‘int’
prob4.cpp:6:12: error: ‘fun2’ was not declared in this scope
[****@storm homework]$


On line 6, you're re-declaring that x is an int - don't do that.
Also, fun2 doesn't even exist at line 6 yet - you need to either move its definition or forward-declare that it exists.
Lastly, fun1 needs to return a value (because it says it does)

Oh, and probably you want to print the value of x between and after calling each function.
Last edited on
So would something like the code below be correct for "correcting" the problem?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int fun1(int x)
{
   x=3*x;
   return x;
}
int fun2(int& y)
{
   y=3*y;
   return y;
}
int main()
{
   int x=2;
   cout << fun1(x) << endl;
   cout << fun2(x) << endl;
}
Fixed!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

int fun1(int& x);
int fun2(int& y);


int fun1(int& x)
{
   return fun2(x);
}
int fun2(int& y)
{
   y=3*y;
   return y;
}
int main()
{
   int x=2;
   cout << fun1(x) << endl;
   cout << fun2(x) << endl;
}


Topic archived. No new replies allowed.