Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I've seen style guides recommend that to avoid typos on == that accidentally result in assignment: write "123 == foo" instead of "foo == 123" so that you can't accidentally write "foo = 123".


Surely such code would be caught by some other tool, and isn’t worth the mental overhead to translate it back into the more natural form?


It's not only about not accidentally writing `if (x=0)`.

The `if (0==x)` style also makes it obvious that the check is correct when reviewing/reading code. Sure, a linter might catch this. But this way the reader doesn't need to rely on that. Besides many codebases allow variable assignment as part of conditional/loop expressions, and sometimes sadly it's easier to write code this way than to get a team to use a linter.

Regarding it being unnatural... you get used to it, and especially in C one needs to take care to check the return code the right way (0!=, 0==, -1!=, 0<, !, etc.), whereas the other side of the check is often more straightforward (a function call, a variable etc.), so it's nice to have the constant up front. It takes very little extra space at the front. As a bonus all the constants will visually line up nicely that way.


Both GCC and Clang have -Wparentheses, enabled with -Wall, which will warn on constructs like `if(x=0)`. MSVC also has a warning for this.


"Natural" is both not universal, and re-trainable. `value [op] var` is quite common in many circles, it is natural to many of those coders.


> Surely such code would be caught by some other tool

This technique was invented back in the 1980s, back then compilers have no static analysis capabilities that we take for granted today. I think the reason of keep using it in 2020 is a matter of habit.


It's caught by the compiler since you can't assign to a constant. Why would you need another tool?


Or we can take advantage of our compilers instead of mountains of untested linting cruft.


I can get on board with this, as it scans the same both directions




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: