Good programming practices - constants on LHS in conditions


In languages where = is used for assignment and == is used for comparison ( C,C++ and languages with similar rules ) , this is a good programming practice that saves us a lot of potential trouble later in the form of program malfunction and debugging effort.

I think I first read about this in the excellent book titled "Writing Solid Code" by Steve Maguire.

So what is it. As shown in the picture in green. If you have to compare a variable with a constant value , then it is advisable to have the constant on the left hand side of the comparison operator '==' . This is because in the case you by error write the assignment operator '=' , it will throw a compiler error and will force you to correct your code accordingly.


As opposed to this , if you have the constant on the right hand side of the comparison operator and make the same mistake , there will be no error and the assignment will just take place.

I cannot begin to tell you how many times I have seen people being hit by problems that this causes . Something that is very easy to avoid if you make a habit of having the constant on the left hand side.


Muhammad Arif

SIP | IMS | VoLTE | Embedded systems | Network Programming | LTE | V2X

3 个月

isn't it a bit old now?

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了