0
Why after Function manipulation the value still same as before function?
#include <iostream> using namespace std; int myFunc(int var) { var = 100; } int main() { int var = 20; myFunc(var); cout << var; } /* Output: 20 Based on code from lesson: https://code.sololearn.com/250/#cpp */
3 odpowiedzi
+ 5
because in this code when you are calling the function it creates local variable var in function(myFunc) and copies the passed argument so changes the value of that local variable(var). so the var in main stays the same because of copying.
if you want to actually change the value pass it by reference like this:
int myFunc(int& var){
var = 100;
}
+ 2
i will note that in the end of myFunc and main you should make them return something, since these functions have a non-void type (int in this case, so they should return int) (preferably return 0 for main, myFunc can return var).
with that said, you could rewrite your code to fit with your goal.
Firstly you add "return var;" to the end of myFunc, which makes it return the value of var.
Secondly you rewrite "myFunc(var);" to
"var = myFunc(var);", this will make var take the value of whatever the function var returns, which is what you need
buut Tanays method is more clear, with mine you dont have to dig into references (& thing) and stuff. Also following Tanays method, you could change myFunc int type to void, as it doesent have to return anything
+ 1
Thanks Tanay.
Maybe I'm going too further with my experiment with functions. :)