I’m mixing up two ideas in C++. Both can make a changed value show up later, but I’m not sure what each one is actually for. Could someone explain the difference simply?
What’s the simple difference between pass-by-reference and static variables?
Answers
They solve different problems. A reference lets a function work with a variable the caller already has, rather than a separate copy. A local static variable belongs to the function and keeps its value between calls.
So one is about which variable the function uses. The other is about how long a variable inside the function sticks around.
Reply to this answer
Here’s a small example:
void add_one(int& n) { ++n; }
If the caller passes in a variable, add_one changes that same variable. The function doesn’t keep it for the next call. If you call the function again, the caller can pass a different variable.
By contrast, static int count = 0; inside a function creates one function-local variable that keeps its value after the function returns. It’s initialized once, then reused on later calls. The caller doesn’t choose which variable it is.
Reply to this answer
Think of a reference as borrowing someone else’s notebook. The caller picks the notebook, and changes made through the reference are visible to them.
A static local is more like a notebook kept in the function’s desk. It’s still there next time the function runs, even though the function has returned. That persistence can make the two seem alike, but they’re not interchangeable.
Reply to this answer
One detail that helps: a static local variable is not a global variable, because its name is still only accessible inside the function where it’s declared. But its lifetime lasts for the whole program, rather than ending when that function call ends.
A reference parameter doesn’t extend the caller’s variable lifetime. It just gives the function another way to refer to that existing variable while the call is happening.
Reply to this answer
Add your answer
Answers are reviewed before publication.
6N!Burlapwork:
So if I want a function to update a value that the caller supplies, I should use a reference, and if I want the function to remember its own value, I should use static?
92Pancake:
Yes, that’s the basic distinction. Also, a function can use both, or neither, depending on what it needs to do.