Using assignment as a condition expression?

前端 未结 5 1852
北荒
北荒 2020-11-28 13:06

Consider:

if (a=5) {
   /* do something */
}

How does the assignment work as a condition?

Is it based on non-zero value of l-value?

5条回答
  •  天涯浪人
    2020-11-28 13:34

    Yes, it is based on the zero/non-zero value which a is assigned. To some people (myself included) it is also considered bad practice to have expressions with side-effects in your code, so the mentioned code fragment would preferably be written as something like

    a = 5;
    ...
    if (a != 0) {
        ...
    }
    

提交回复
热议问题