301 views
8 8 votes

What is the output of the following code?

#include <stdio.h>

void fun() {
    static int x = 1;

    x = x + 2;

    printf("%d ", x);
}

int main() {
    fun();
    fun();
    fun();

    return 0;
}
  1. $\texttt{3\ 3\ 3}$
     
  2. $\texttt{3\ 5\ 7}$
     
  3. $\texttt{1\ 3\ 5}$
     
  4. $\texttt{2\ 4\ 6}$

2 Answers

3 3 votes

Option B

1 1 vote

Here, $\texttt{x}$ is a static local variable.

A static local variable is initialized only once and keeps its value between function calls.

Initially, $\texttt{x = 1}$.

In the first call, $\texttt{x = 1 + 2 = 3}$, so it prints $\texttt{3}$.

In the second call, $\texttt{x}$ starts from old value $\texttt{3}$.

So, $\texttt{x = 3 + 2 = 5}$, and it prints $\texttt{5}$.

In the third call, $\texttt{x}$ starts from old value $\texttt{5}$.

So, $\texttt{x = 5 + 2 = 7}$, and it prints $\texttt{7}$.

Therefore, the output is $\texttt{3\ 5\ 7}$.

Answer: B

Answer:
Position:
Show:

Related questions

8 8 votes
2 2 answers
254
254 views
GO Classes asked Jun 9
254 views
What is the output of the following code?#include <stdio.h int x = 10; int main() { int x = 20; printf("%d", x); return 0; }
7 7 votes
3 3 answers
291
291 views
GO Classes asked Jun 9
291 views
What is the output of the following code?#include <stdio.h int main() { register int x = 10; int *p = &x; printf("%d", *p); return 0; }$\texttt{10}$ $\texttt{0}$ Garbage ...
9 9 votes
2 2 answers
260
260 views
GO Classes asked Jun 9
260 views
What can be said about the output of the following code?#include <stdio.h int main() { auto int x; printf("%d", x); return 0; }Output is always $\texttt{0}$ Output is alw...
9 9 votes
2 2 answers
256
256 views
GO Classes asked Jun 9
256 views
What is the output of the following code?#include <stdio.h int a; static int b; int main() { printf("%d %d", a, b); return 0; }$\texttt{0\ 0}$ Garbage values $\texttt{1\ ...