247 views
8 8 votes

What is the output of the following code?

#include <stdio.h>

int main() {
    int a = 8, b = 12;
    int *p = &a;
    int *q = &b;

    *p = *p + *q;
    q = p;
    *q = *q - 5;

    printf("%d %d", a, b);

    return 0;
}
  1. $\texttt{15\ 12}$
     
  2. $\texttt{20\ 12}$
     
  3. $\texttt{15\ 15}$
     
  4. $\texttt{8\ 12}$

1 Answer

2 2 votes

Initially, $\texttt{a = 8}$ and $\texttt{b = 12}$.

Pointer $\texttt{p}$ points to $\texttt{a}$ and pointer $\texttt{q}$ points to $\texttt{b}$.

The statement $\texttt{*p = *p + *q}$ changes $\texttt{a}$.

So, $\texttt{a = 8 + 12 = 20}$.

Now, $\texttt{q = p}$ means $\texttt{q}$ also starts pointing to $\texttt{a}$.

So now both $\texttt{p}$ and $\texttt{q}$ point to $\texttt{a}$.

The statement $\texttt{*q = *q - 5}$ again changes $\texttt{a}$.

So, $\texttt{a = 20 - 5 = 15}$.

The value of $\texttt{b}$ remains $\texttt{12}$.

Therefore, the output is $\texttt{15\ 12}$.

Answer: A.

Answer:
Position:
Show:

Related questions

8 8 votes
1 1 answer
241
241 views
GO Classes asked Jun 6
241 views
What is the output of the following code?#include <stdio.h void change(int *p, int *q) { *p = *p + 4; *q = *p + *q; p = q; *p = *p - 3; } int main() { int a = 6, b = 10; ...
9 9 votes
1 1 answer
226
226 views
GO Classes asked Jun 6
226 views
What is the output of the following code?#include <stdio.h int main() { int i, j, count = 0; for (i = 1; i <= 4; i++) { for (j = 1; j <= 4; j++) { if (i * j 6) break; co...
8 8 votes
1 1 answer
210
210 views
GO Classes asked Jun 6
210 views
What is the output of the following code?#include <stdio.h int calc(int n) { if (n == 1) return 2; return n + calc(n - 1); } int main() { printf("%d", calc(4)); return 0;...
8 8 votes
1 1 answer
245
245 views
GO Classes asked Jun 6
245 views
What is the output of the following code?#include <stdio.h void fun() { static int x = 3; int y = 2; x = x + y; y = y + x; printf("%d ", x); } int main() { fun(); fun(); ...