i encountered to this function
void reverseArray(int *a,int n)
{
for(int i=0,j=n-1;i<j;i ,j--)
{
a[i]^=a[j]^=a[i]^=a[j];
}
}
which is reversing a given array but I can't wrap my mind around how does this reverse an array, isn't Xor operator only returns the non-common bits. so what's the logic behind this to reverse the given array.
CodePudding user response:
a ^= b ^= a ^= b;
is a fancy way to swap two numbers, known as XOR swap.
You should prefer a much more readable std::swap
, or (in C) a temporary variable.
CodePudding user response:
The purpose of the expression a^=b^=a^=b
is to exchange the values of a
and b
. It becomes more clear if we split it up (where a_0
and b_0
are the original values of a
and b
):
- First assignment,
a^=b
makesa_1=(a_0^b_0)
. - Second assignment,
b^=a
makesb_1=(b_0^a_1)=(b_0^(a_0^b_0))=a_0
- Third assignment,
a^=b
makesa_2=(a_1^b_1)=((a_0^b_0)^a_0)=b_0
Thus we end up with a
having the original value of b
and vice versa.
While the expression a^=b^=a^=b
may work it is actually undefined behavior because the C standard does not specify the order of assignments. Instead, it must be sequenced explicitly: a^=b; b^=a; a^=b;
.