in Programming in C edited by
426 views
0 votes
0 votes
#include <stdio.h>

int main()

{

int x = -5, y = 8;

x = x + y - (y = x);

printf("%d", x * y);

return 0;

}



what will be the o/p for this? and what is the logic?

in Programming in C edited by
426 views

2 Answers

2 votes
2 votes
Best answer

 

initially x= -5 and y= 8

then x= x+y-(y=x)

now based on priority and associativity rules of c

x= -5+8-(y=-5)

so y is assigned with value of x that is y= -5 from now onwards

x= -5+8-y

x=3-(-5)

x=8

 

now in printf x*y done so x=8 and y=-5 so 8*(-5) = -40  

so finally -40 printed.

 

selected by

4 Comments

x = x + y - (y = x);
 

to complete this expression right side will be evaluated first so go to right side

x+y-(y=x) so it will be break down as

t1= x+y = -5+8 =3 then

t2= (y=x) so y= -5 now

t3 = t1- t2 = 3-(-5) = 8.

yes i agree precedence rule says bracket first but for that you have to reach to bracket , you can't directly jump to bracket na.

compiler will scan left to right so while going right in between if bracket there and if it is needed to be done then only bracket will be executed.

 i hope you get it.
0
0
tell me onething why you are not executing (y=x) first ?(since it has high precedence value )
0
0
buddy when we go from left to right in   x + y - (y = x);

x seen by compiler then + then y

now if you have both operands then perform operation

so x+y done assume it as t1

now our expression is  t1-(y=x) now t1 seen by compiler then –  then (y=x) so do (y=x) then

so it becomes t1-y (y is updated one ).
1
1
1 vote
1 vote

 

  1. Initialize variables:

    • x is set to -5.
    • y is set to 8.
  2. Expression x = x + y - (y = x);:

    • As mentioned before, the order of evaluation is not guaranteed in C, and this expression attempts to swap the values of x and y.
    • The expression can be rewritten as: x = (-5) + 8 - (y = -5);
    • When evaluating y = -5, the value -5 is assigned to y.
    • Now the expression becomes: x = (-5) + 8 - (-5);
    • Simplifying further, x = (-5) + 8 + 5;
    • Finally, x = 8, as -5 + 8 + 5 = 8.
  3. printf("%d", x * y);:

    • Here, the program prints the result of x * y.
    • Since x is 8 and y is still 8 (as it was assigned the value -5 and not modified afterward), the result of x * y is 8 * 8, which is -40.

So, the output of the code is indeed -40