Why does C not have a logical assignment operator?

前端 未结 4 589
面向向阳花
面向向阳花 2020-12-29 21:00

I had the need to code a statement of the form

a = a || expr;

where expr should be evaluated and the result be assigned to <

4条回答
  •  执笔经年
    2020-12-29 21:31

    Because the return type of operators || and && is not the same as type of their left argument.

    The return type of || and && is always int1, while the left argument may be any integral, floating point or pointer type. The operands also don't have to be of the same type. Therefore defining x ||= y as x = x || y and x &&= y as x = x && y as would be consistent with other augmented assignments would not be able to store the result in the argument for most types.

    You could come up with other definitions, e.g. x ||= y as if(!x) x = y and x &&= y as if(!y) x = y, but that would not be exactly obvious and it is not that useful, so it was not included.

    1In C++ it is bool.

提交回复
热议问题