-1

In C what does this statement do?

*p1 ^= *p2;

p1 and p2 are char pointers pointing to two different address of a char array. I know about ^ operator is XOR.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Sarfaraz
  • 7
  • 1
  • 1
    If you know about `^` then you know what that statement does. – Hatted Rooster Oct 14 '17 at 16:25
  • XORing the data pointed by the two and storing the result in the address pointed by `p1`. – Eugene Sh. Oct 14 '17 at 16:26
  • 1
    ^ is the exclusive or operator. a ^= b is an abbreviation of a = a ^ b. – Xaver Oct 14 '17 at 16:26
  • The `^=` is a single operator. You may be more familiar with its analog, `+=`. The effect of the statement follows directly from the behavior of the operators involved in it, `*` and `^=`, which you certainly are capable of looking up for yourself if you need to do. – John Bollinger Oct 14 '17 at 16:26
  • 1
    It's the same as `*p1 = *p1 ^ *p2`. "The value of p1 is set to the value of p1 xored with the value of p2." In the case where the char pointers are both pointing to 2, it changes the value of p1 to 0. (Because a ^ a = 0) – OmnipotentEntity Oct 14 '17 at 16:27
  • @EugeneSh. Thanks – Sarfaraz Oct 14 '17 at 16:28

4 Answers4

2

It should probably be easier to understand if you see it this way instead:

char c1 = *p1;
char c2 = *p2;

c1 = c1 ^ c2;

*p1 = c1;

That's basically what the code you show is doing.

This of course relies on you knowing how exclusive or actually works, and know about pointer dereferencing too.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

This

*p1 ^= *p2;

is the compound assignment operator with the bitwise exclusive OR operator,

It is a substitution for this expression statement

*p1 = *p1 ^ *p2;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

When apply ^ on char variable, just regard it as int.

define VALUE 11
char c = VALUE;
int i = VALUE;

Cause you can think that the value of c or i are same in memory.

HolaYang
  • 419
  • 2
  • 10
0

The bitwise exclusive OR operator (^) compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise exclusive OR operator must be of integral types. The usual arithmetic conversions covered in Arithmetic Conversions are applied to the operands.