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;
}

  1. A.

    5 14

  2. B.

    5 9

  3. C.

    14 5

  4. 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.

  1. Initial Values: x = 5, y = 9.

  2. Evaluating the Parentheses:

    • First sub-expression (x = x + y): x becomes 5 + 9 = 14. The value of this sub-expression is 14.

    • Second sub-expression (y = x - y): Now, x is 14. So, y becomes 14 - 9 = 5. The value of this sub-expression is 5.

  3. Final Assignment for x:

    • x = (14) - (5) = 9.

  4. Final Result: x = 9, y = 5.

Explore the full course: Coal India Management Trainee