#include <iostream>
#include "stdafx.h"
usingnamespace std;
int MyFunction2()
{
int x = 4;
cout << "You are in MyFunction2\n";
return x;
}
int MyFunction1(int a)
{
int y = 3;
int z;
cout << "You are in MyFunction1\n";
MyFunction2();
cout << "You are back in MyFunction1\n";
a + y = z;
return z;
}
int main()
{
cout << "You are in main\n";
MyFunction1();
cout << "You are back in main\n";
cout << main();
char f;
cin >> f;
return 0;
}
When I do this, I get a red line under "MyFunction1()" in the line "MyFunction1() + y = z;". When I hover over it, it says "expression must be a modifiable lvalue".
I was under the impression that if you returned a value, the function then "held" that value, so I could do calculations with it or whatever I wanted.
I also tried doing something different, but I get the same error under "a".
1 2 3 4 5 6 7 8 9
int MyFunction1(int a)
{
int y = 3;
int z;
cout << "You are in MyFunction1\n";
MyFunction2();
cout << "You are back in MyFunction1\n";
a + y = z;
return z;
The problem is the way you have the equation set up, not the function itself.
It should be z = a + y; not a + y = z
You also seem to be misunderstanding returning values from functions slightly.
For example in main you call function1 and return z, but you don't set that return value equal to anything so it just disappears.
If you want to use return values from functions correctly you will want to do something like this.
1 2 3 4
int main()
{
int z = MyFunction1(); // gets whatever value MyFunction1 returned and puts it in z
}
Now the value 'z' will hold whatever was returned from the function.
(On a side note you aren't passing anything into Function1, when you should be).
Thank you James! So basically, you need to assign something to receive what is being returned? So what is happening when you create a function like this
int main(int x, int z, int y, int h)? Are you just declaring/creating those integers? Does that have anything to do with returning?
Yes you need to assign a variable to a function to receive the value it is returning. As for your other question those are called function parameters, and are not really related to returning values.
1 2 3 4 5 6 7 8 9 10 11 12 13
// x,y,z = function parameters, when calling the function you will need to pass 3 values into it in this case.
int Function(int x, int y, int z)
{
cout << x << y << z << endl; // will print out 10,12,15
return (x + y + z); // returns value back to main
}
int main()
{
int Result = Function(10,12,15); // stores return value in Result
cout << Result << endl; // will print out 10 + 12 + 15 (37).
}