Difference between if(a==1) & if(1==a)

【premise】

When the company participated in the project, I saw that the seniors wrote if to compare whether the values ​​were equal, and often wrote if(1==a), which felt a little strange. If so, write down the survey results and record them.

 

【result】

There is no difference between if(a==1) and if(1==a), but it is a good way to avoid errors "accidentally" generated by programmers when coding

 

If you are used to writing if (a==1), if the programmer "accidentally" writes one less equal sign, it becomes an assignment meaning, which will not be detected in the compiler, and the result will be wrong.

But if you write if(1==a), if there is one less equal sign, then the compiler will report an error --> because when there is one less equal sign, that is, the assignment operation, the left side cannot be a constant

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324594527&siteId=291194637