15.3k views
3 votes
What will the following code display? #include using namespace std; void doSomething(int); int main() { int x = 2; cout << x << " "; doSomething(x); doSomething(x); cout << x << endl; return 0; } void doSomething(int num) { static int x = 0; cout << x << " "; x=num; }

User Durin
by
3.5k points

1 Answer

3 votes

Answer:

The output will be: 2 0 2 2

Step-by-step explanation:

First of all, you need to complete the statement "#include". It is "#include <iostream>".

Static variables in a Function: When a variable is declared as static, space for it gets allocated for the lifetime of the program. Even if the function is called multiple times, space for the static variable is allocated only once and the value of variable in the previous call gets carried through the next function call.

User Xsukax
by
4.0k points