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

前端 未结 4 1931
故里飘歌
故里飘歌 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:24

    To understand such expressions, you have to first understand that, positive integers are considered as 'true' and 0 is considered as false.

    An assignment evaluates to the left hand side of the operator = as its value. So, while(a=b) { } would mean, while(1 /*true*/) if a after being assigned to b evaluates to non-zero. Else, it is considered as while(0 /*false*/)

    Similarly, with the operator (a=b)?1:0 is the value of a after being assigned to b .. if it is non-zero then the value is taken as true and the statement following ? will be executed, or the statement following : is executed.

    Assignments usually evaluate to the value at the left hand side of the operator = where as, logical operators(such as ==, && etc) evaluate to 1 or 0.

    Note: with C++, it will depend upon if or not, a certain operator is overloaded.. and it will also depend upon the return type of the overloaded operator.

提交回复
热议问题