I'm answering your title, which is "How can a function “remember” it's result for its next use?". Your title implies the general case, and I'm not interested in the particular function in your question body.
First, I'd like to say kudos to Python for the yield
keyword, unfortunately, in C there is no such syntactic sugar.
So the most correct answer is NO, you cannot do that in C, and no, static is not the answer.
Static is not reentrant. Sometimes a simple no, you cannot do that, not for real, not in C, is better than telling you half-baked solutions. C just doesn't have this feature, and that's it.
Python has yield
, C doesn't. The end.
You'll have to simulate it by using a struct to hold the state.
Some pseudo-code:
struct State { ... };
Output foo(struct State *state, ...) { ... }
...
foo(&state);
foo(&state);
If you don't want to do it the right way, then use static and spend 2-3 days figuring out bugs when you try to nest a call to the function. strtok
has bitten people that way.
Note that using static
might make the function not reentrant. Be careful:
Output foo(...) { static struct State state; ... }
Addendum
Functions in the mathematical sense are by definition stateless. If it has state, then it's an object, not a function. A function with static state is semantically really a singleton object.
State implies memory, and memory + methods = object.