C
Programming and Technical
main()
{
int a=10,b=20;
a^=b^=a^=b;
printf("%d%d",a,b);
a) a=20,b=10
b) a=10,b=20
c) Syntax error
d) Unpredictable
Ans : a=20 b=10
can somebody conclude it.
Read Solution (Total 5)
-
- This program is to swap the contents of a and b using ex-or operator.
^= is short-hand assignment i.e. (a ^= b)is equivalent to (a = a ^ b)
As assignments are right associative (i.e. = ,+=, -=, *=, ^= are evaluated right to left when assignments are cascaded).
Thus statement :
a^=b^=a^=b is equivalent to (a = a ^ (b = b ^ (a = a ^ b)))
Performing bitwise ex-or operation contents of a and b are swapped. - 11 years agoHelpfull: Yes(6) No(0)
- if prog is as it is... then there will be 1 error(since '{}' is not completed) and 1 warning(return value is not mention (e.g. void main())
=> [for the statement, int a=10,b=20;
a^=b^=a^=b; ans:a=20,b=10]
=> x^=y => x=x^y (where ^ is bitwise exclusive OR)
for statement a^=b^=a^=b;
=> (right to left) a^=b => a=a^b
a=10^20= 01010^10100 =11110 (will save in a)
now, a^=b^=a
b^=a => b=b^a
=>b=10100^11110=01010 (decimal value 10)
again, a^=b
(but here a=11110,b=01010) a= a^b= 11110^01010=10100(decimal value 20)
=>a=20 & b=10 - 11 years agoHelpfull: Yes(4) No(0)
- a^=b^=a^=b;
/*
This can be written as follows (right to left)
->
1.a^=b;
2.b^=a;
3.a^=b;
step 1:
01010:a=10
10100:b=20
-----------(performing exclusive or)
11110:a=30 (step-1 result)
10100:b=20
11110:a=30
-----------(xor)
01010:b=10(step-2 result)
11110:a=30
01010:b=10
----------
10100:a=20(step-3 result)
finally:
10100:a=20
01010:b=10
*/ - 11 years agoHelpfull: Yes(3) No(0)
- a)a=20,b=10
- 11 years agoHelpfull: Yes(0) No(0)
- starting from right
new_a1=a+b
new_b=b+new_a=b+a+b=a
new_a2=new_a1a+new_b=a+b+a=b
thus now a and b are inverted - 11 years agoHelpfull: Yes(0) No(0)
C Other Question