Find the output of the following #include<stdio.h> int main() { int x = 5, y =…
2020
Find the output of the following
#include<stdio.h>
int main()
{
int x = 5, y = 9;
x = (x = x + y) - (y = x - y);
printf("%d %d", x, y);
return 0;
}
- A.
5 14
- B.
5 9
- C.
14 5
- D.
9 5
Attempted by 933 students.
Show answer & explanation
Correct answer: D
The core of this problem lies in the expression: x = (x = x + y) - (y = x - y);. This is an example of an expression that technically results in undefined behavior in standard C because it modifies the same variable multiple times without a sequence point. However, most modern compilers (and competitive exam environments) evaluate it using a specific mathematical sequence.
Initial Values:
x = 5,y = 9.Evaluating the Parentheses:
First sub-expression
(x = x + y):xbecomes 5 + 9 = 14. The value of this sub-expression is 14.Second sub-expression
(y = x - y): Now,xis 14. So,ybecomes 14 - 9 = 5. The value of this sub-expression is 5.
Final Assignment for x:
x = (14) - (5) = 9.
Final Result:
x = 9,y = 5.