Low level details of C/C++ assignment operator implementation. What does it return?

前端 未结 4 1933
故里飘歌
故里飘歌 2020-12-16 22:36

I m a total newbie to a C++ world (and C too). And don\'t know all its details. But one thing really bothers me. It is constructions like : while (a=b) {...} .

4条回答
  •  臣服心动
    2020-12-16 23:10

    For built-in types in C++ evaluating an assignment expression produces an lvalue that is the left hand side of the assignment expression. The assignment is sequenced before the result can be used, so when the result is converted to an rvalue you get the newly assigned value:

    int a, b=5;
    int &c = (a=b);
    assert(&c==&a);
    b=10;
    assert(10==(a=b));
    

    C is almost but not exactly the same. The result of an assignment expression in C is an rvalue the same as the value newly assigned to the left hand side of the assignment.

    int *c = &(a=b); // not legal in C because you can only take the address of lvalues.
    

    Usually if the result of an assignment is used at all it's used as an rvalue (e.g., a=b=c), so this difference between C++ and C largely goes unnoticed.

提交回复
热议问题