Back to questions
JuniorTheoryCommon
What does the program print?
#include <iostream>
int add(int x) {
static int total = 0;
total = total + x;
return total;
}
int main() {
int total = add(5);
std::cout << add(2) << ' ' << total << '\n';
}7 5
- Expecting
2 5: astaticlocal is initialized once, not on every call, so the second call adds2to the5it kept. - Expecting
7 7:staticchanges how longtotalinaddlives, not where it is visible, sototalinmainis a separate variable.
- How would the output change if
totalinaddwere declared withoutstatic? - Is it safe to call a function with a
staticlocal from several threads at once?