438 views
13 13 votes

What is the output of the following code?

#include <stdio.h>

int main() {
    int a = 0, b = 5, c = 10;
    int ans = a++ && ++b || c--;

    printf("%d %d %d %d", ans, a, b, c);
    return 0;
}
  1. $\texttt{1\ 1\ 6\ 9}$
     
  2. $\texttt{1\ 1\ 5\ 9}$
     
  3. $\texttt{0\ 1\ 5\ 10}$
     
  4. $\texttt{1\ 0\ 5\ 9}$

3 Answers

5 5 votes

The expression is $\texttt{a++ \&\& ++b || c--}$.

The operator $\texttt{\&\&}$ has higher precedence than $\texttt{||}$.

So the expression is evaluated as $\texttt{(a++ \&\& ++b) || c--}$.

Initially, $\texttt{a = 0}$, $\texttt{b = 5}$, and $\texttt{c = 10}$.

In $\texttt{a++}$, the current value $0$ is used first, and then $\texttt{a}$ becomes $1$.

Since the first operand of $\texttt{\&\&}$ is $0$, the second operand $\texttt{++b}$ is not evaluated due to short-circuit evaluation.

So, $\texttt{b}$ remains $5$.

Now the expression becomes $\texttt{0 || c--}$.

In $\texttt{c--}$, the current value $10$ is used first, and then $\texttt{c}$ becomes $9$.

Since $10$ is non-zero, it is treated as true.

Therefore, $\texttt{ans = 1}$.

Final values are $\texttt{ans = 1}$, $\texttt{a = 1}$, $\texttt{b = 5}$, and $\texttt{c = 9}$.

Answer: B. $\texttt{1\ 1\ 5\ 9}$

Answer:
Position:
Show:

Related questions

10 10 votes
3 3 answers
397
397 views
GO Classes asked Jun 3
397 views
What is the output of the following code?#include <stdio.h int main() { int a = 1, b = 2, c = 3; if (a++ 1 && ++b 2 || c++ == 3) printf("%d %d %d", a, b, c); else print...
5 5 votes
2 2 answers
379
379 views
GO Classes asked Jun 2
379 views
What is the output of the following code?#include <stdio.h int main() { int i, sum = 0; for (i = 1; i <= 6; i++) { if (i % 2 == 0) continue; sum = sum + i; if (sum 6) br...
7 7 votes
2 2 answers
313
313 views
GO Classes asked Jun 2
313 views
What is the output of the following code?#include <stdio.h int main() { int a = 5, b = 2; float x = a / b + 0.5; printf("%.1f", x); return 0; }
7 7 votes
2 2 answers
284
284 views
GO Classes asked Jun 2
284 views
What is the output of the following code?#include <stdio.h int main() { float x = 5 / 2; printf("%.1f", x); printf(" "); float y = 5.0 / 2; printf("%.1f", y); return 0; }...