Hacker News new | ask | show | jobs
by throwaway3neu94 1775 days ago
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.

1 comments

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.