Question
Download Solution PDFConsider the following statements
int x = 10, y = 15;
x = ((x = y) ? (y + x) : (y - x));
What will be the value of x after executing these statements?
Answer (Detailed Solution Below)
Option 4 : 30
Detailed Solution
Download Solution PDFThe correct answer is 30.
Key Points
- Let's break down the given code to understand how the value of
x
becomes 30. - The initial values are:
int x = 10;
int y = 15;
- Next, we have the statement:
x = ((x = y) ? (y + x) : (y - x));
- In the statement
(x = y)
,x
is assigned the value ofy
, so nowx = 15
. - In the ternary conditional operator
((x = y) ? (y + x) : (y - x))
, sincex = y
results inx
being non-zero (true in a Boolean context), the condition is true. - When the condition is true, the expression
(y + x)
is evaluated.y
is 15 andx
is now 15, soy + x = 15 + 15 = 30
.
- Therefore,
x = 30
after the assignment.
Additional Information
- The ternary conditional operator is a shortcut for the
if-else
statement and is used to assign one of two values based on a condition. - Syntax:
condition ? value_if_true : value_if_false
. - It's important to understand the order of evaluation and assignment in expressions to correctly determine the resulting values of variables.
- In this example, the assignment
(x = y)
happens first, followed by the evaluation of the ternary condition and the resulting expression.