Two Equal Signs in One Line?

后端 未结 10 873
北荒
北荒 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:32

    You can do this: http://en.wikibooks.org/wiki/C_Programming/Variables

    Moreover,

    [a int] = 0; is possible.

    [a char] = 0; is possible too.

    arcbit and arcchar equals 0.

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

    Assignment in C is an expression, not statement. Also you can freely assign values of different size (unsigned char to int and vice versa). Welcome to C programming language :)

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

    It assigns ArcBit to 0, then assigns ArcChar to the value of the expression ArcBit = 0 (ie. 0)

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

    That is just chaining of the assignment operator. The standard says in 6.5.16 Assignment operators:

    An assignment operator shall have a modifiable lvalue as its left operand. An assignment operator stores a value in the object designated by the left operand. An assignment expression has the value of the left operand after the assignment, but is not an lvalue. The type of an assignment expression is the type of the left operand unless the left operand has qualified type, in which case it is the unqualified version of the type of the left operand. The side effect of updating the stored value of the left operand shall occur between the previous and the next sequence point.

    So you may do something like:

    a=b=2; // ok
    

    But not this:

    a=2=b; // error
    
    0 讨论(0)
  • 2020-12-06 05:42
    ArcChar = ArcBit = 0;
    

    The assignment is left-associative, so it's equivalent to:

    ArcChar = (ArcBit = 0);
    

    The result of ArcBit = 0 is the newly-assined value, that is - 0, so it makes sense to assign that 0 to ArcChar

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

    The value of the expression (a = b) is the value of b, so you can chain them this way. They are also right-associative, so it all works out.

    Essentially

    ArcChar = ArcBit = 0;
    

    is (approximately1) the same as

    ArcBit = 0;
    ArcChar = 0;
    

    since the value of the first assigment is the assigned value, thus 0.

    Regarding the types, even though ArcBit is an unsigned char the result of the assignment will get widened to int.


    1   It's not exactly the same, though, as R.. points out in a comment below.

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