+ 2

How can a function save previous argument that was passed to it?

My function needs to know the value of a previous argument that was passed to it. For example if I call this function twice, it needs to know the value passed to it in the first call to take action. How can I achieve this?

13th Dec 2019, 11:20 PM
mel1705
mel1705 - avatar
2 Respostas
+ 5
And that would be so nice if only C had classes. 🙄 Here's how you can do it in C: #include <stdio.h> void f(int n) { static int m = 0; printf("Old: %d", m); m = n; printf("\nNew: %d\n\n", m); } int main() { f(3); f(5); f(7); return 0; }
13th Dec 2019, 11:49 PM
HonFu
HonFu - avatar
+ 1
You will have to make a variable independent from the function. Declare it outside of the function and you can instantiate it inside the function. Here's some pseudocode: class MyClass { var myVar static func x(b?) { if (myVar == null && b != null) { myVar = b * 2 } else { print(myVar) } } } func main() { MyClass.x(5) MyClass.x() }
13th Dec 2019, 11:48 PM
Brian R
Brian R - avatar