Two Equal Signs in One Line?

后端 未结 10 874
北荒
北荒 2020-12-06 04:58

Could someone please explain what this does and how it is legal C code? I found this line in this code: http://code.google.com/p/compression-code/downloads/list, which is a

相关标签:
10条回答
  • 2020-12-06 05:47

    In some languages, assignments are statements: they cause some action to take place, but they don't have a value themselves. For example, in Python1 it's forbidden to write

    x = (y = 10) + 5
    

    because the assignment y = 10 can't be used where a value is expected.

    However, C is one of many languages where assignments are expressions: they produce a value, as well as any other effects they might have. Their value is the value that is being assigned. The above line of code would be legal in C.

    The use of two equals signs on one line is interpreted like this:

    ArcChar = (ArcBit = 0);
    

    That is: ArcChar is beging assigned the value of ArcBit = 0, which is 0, so both variables end up being 0.


    1 x = y = 0 is actually legal in Python, but it's considered a special-case of the assignment statement, and trying to do anything more complicated with assignments will fail.

    0 讨论(0)
  • 2020-12-06 05:48

    As Hasturkun said, this is due to operator associativity order C Operator Precedence and Associativity

    0 讨论(0)
  • 2020-12-06 05:51

    An assignment operation (a = b) itself returns an rvalue, which can be further assigned to another lvalue; c = (a = b). In the end, both a and c will have the value of b.

    0 讨论(0)
  • 2020-12-06 05:53

    It sets both variables to zero.

    int i, j;
    i = j = 0;
    

    The same as writing

    int i, j;
    j = 0;
    i = j;
    

    or writing

    int i, j;
    i = 0;
    j = 0;
    
    0 讨论(0)
提交回复
热议问题