Value of an integer remains the same after calling a function with it as a parameter | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Value of an integer remains the same after calling a function with it as a parameter

The relevant chunk of the code is this: #include <iostream> using namespace std; void Test(int x){ cout << x << endl; x=x+1; cout << x << endl; } int main(){ int g = 0; Test(g); Test(g); Test(g); So the first time the function is called, it outputs '0' on the first line and '1' on the second line, which is what I would expect. The value of my variable, however, resets after the function is ran - it goes back to '0', so when I call it the second time it gives me the same output. Is there a way to make the variable 'remember' it's new value and carry it over into the second time the function is called?

11th Jun 2018, 6:21 PM
Daniel
Daniel - avatar
4 Answers
11th Jun 2018, 6:34 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 5
As Aaron Eberhardt pointed out, the parameter 'x' of Test function takes a copy of original value 'g' by which you feed the function. Every modification on x will be local to the scope of the function and once the program flow returned from that function, x is destroyed. That's what you've seen as the expected output, so far. Basically, when you want to pass and keep track, for example, the value of 'g' between calling and return state of a function you either pass it by reference or pointer. Each have their own pros and cons. For the most part, passing by reference is preferable (still depends on the context in which the function operates and other factors). Also, passing by reference for stl containers instead of value is considered a performance improvement factor in terms of avoiding deep copying. Let's reform the function signature (the only part you need to modify). void Test(int &x) { // body } That's all!
11th Jun 2018, 7:05 PM
Babak
Babak - avatar
+ 2
Yeah, that works, thanks! *I had tried to pass a pointer, but the syntax was wrong. I went over the previous lessons and found that void Test(int &x){ cout << x << endl; x=x+1; cout << x << endl; } int main(){ int g = 0; Test(g); Test(g); Test(g); } Is also correct syntax and does work! Thanks again!
11th Jun 2018, 7:47 PM
Daniel
Daniel - avatar
+ 1
Usually you'd pass a pointer of your variable to the function. Otherwise it will create a new local variable each time you call the function (and delete it once the function has finished).
11th Jun 2018, 6:30 PM
Aaron Eberhardt
Aaron Eberhardt - avatar