What values will be stored in x and y respectively after executing the following?
int = −10, y;
y= − − x;
Answers
Correct Códe:-
int x= −10, y;
y= − − x;
Explanation:
- Initially x=-10
- y= --x means first x will decrease then it will be assigned to y
- y= -- -10
- y=-11
Answer:-
- x= -10
- y= -11
Answer:
int x= -10,y;
y= - -x
Answer:-
Final value of x= -11
Final value of y= -11
Reason:-
- Initially x is -10, y= - -x so,execution starts from right to left.
- -- x is pre increment so the value of y is decremented from -10 to -11 so the final value of y is -11.
- In the same way due to decrement of decrement of x the value of x also changes as the final value of x now becomes -11.
- Note if there is unary operators present in the variable say c like c=++x or c=x++ the value of the variable with which the increment/decrement is used changes.
Example:
int a=10,b;
b=a++;
If u are asked with the final value of b the answer will be
b=10 ,here it is why because it is post increment so the value changes after the action but if you are asked the final value of a then the answer is:
a=11
As the value assigned to b is 10 but the final value of a becomes 11.
So,a=11,b=10;
Case 2:-
Now, if a=10,b;
b= ++a;
If now you are asked the final value of b the answer will be 11 as now it's pre-increment so the value of b will be 11.
Now,if you are asked to find the final value of a then a will be also 11 as we know in unary operators the value of unary operators always changes so as the final value of a=11
So,a=11
Output:-
a=11 and b=11
More information:-
- In post-increment the value is first assigned then incremented.
- In pre-increment the value is first incremented and then assigned.
Hope you understood the concept