Why does C not have a logical assignment operator?

前端 未结 4 597
面向向阳花
面向向阳花 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:44

    I cannot find any particular reason, why the operators don't exist (in C99).

    So the only reason I can find is, that there was no boolean type in C89, and those boolean operators were intended to be solely used in if's.

    Example:

    int i = 5;
    
    /* This should not make any difference,
       since or'ing with false, shouldn't change
       the value... dib di dib diddy...*/
    i ||= 0; /* Actually: i = i || 0, which gives 'true' */
    

    i is now '1'', which for most people is pretty counter intuitive.

    This operator obviously doesn't bring any clearence or coding improvement without the boolean type, that would make sence being or'd with another one.

    In my opinion, the implementation of a ||= b; as if(!a) a = b; would be pretty straightforward and has aleardy been implemented by e.g. Lua.

    So you're question seems to be a bit, why C has been designed the way it has been designed. If this question was about C++, you could for example ask Bjarne Stroustrup and ask him, what had went into him. Since this is not the case, this seems to me to be kind of a dead end, because the standard has been written quite some time ago and you cannot really ask people anymore, why the h***.

    On the other hand, this incomplete operator set should (in my opinion) aleardy have been made whole using a similar notation than yours, since in my opinion, there is no reason against it.

    I hope I could help a little.

提交回复
热议问题