what *p1 ^= *p2; does in c

后端 未结 4 848
别那么骄傲
别那么骄傲 2021-01-29 06:09

In C what does this statement do?

*p1 ^= *p2;

p1 and p2 are char pointers pointing to two different address of a char

相关标签:
4条回答
  • 2021-01-29 06:26

    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.

    0 讨论(0)
  • 2021-01-29 06:28

    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;
    
    0 讨论(0)
  • 2021-01-29 06:29

    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.

    0 讨论(0)
  • 2021-01-29 06:29

    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.

    0 讨论(0)
提交回复
热议问题