When learning to code, I was taught the following style when checking the value of a variable:
int x;
Object *object;
...
if(x == 7) { ... }
if(object == NULL) { ... }
However, now that I am in the field, I have encountered more than one co-worker who swears by the approach of switching the lhs and rhs in the if statements:
if(7 == x) { ... }
if(NULL == object) { ... }
The reasoning being that if you accidentally type = instead of ==, then the code will fail at compile. Being unaccustomed to this style, reading 7 == x is difficult for me, slowing my comprehension of their code.
It seems if I adopt this style, I will likely someday in the future save myself from debugging an x = 7 bug, but in the mean time, every time somebody reads my code I may be wasting their time because I fear the syntax is unorthodox.
Is the 7 == x style generally accepted and readable in the industry, or is this just a personal preference of my coworkers?
True. On the other hand, I believe modern C and C++ compilers (I’m assuming you’re using one of those languages? You haven’t said) will warn you if you do this.
Have you tried it with the compiler you’re using? If it doesn’t do it by default, look to see if there are flags you can use to provoke it – ideally to make it an error rather than just a warning.
For example, using the Microsoft C compiler, I get:
That’s pretty clear, IMO. (The default warning settings don’t spot it, admittedly.)
Indeed. Your approach is the more natural style, and should (IMO) be used unless you’re really dealing with a compiler which doesn’t spot this as a potential problem (and you have no alternative to using that compiler).
EDIT: Note that this isn’t a problem in all languages – not even all C-like languages.
For example, although both Java and C# have a similar
ifconstruct, the condition expression in both needs to be implicitly convertible to a Boolean value. While the assignment part would compile, the type of the expression in your first example would beint, which isn’t implicitly convertible to the relevant Boolean type in either language, leading to a compile-time error. The rare situation where you’d still have a problem would be:which, if typo’d to:
would compile and do the wrong thing. The MS C# compiler even warns you about that, although it’s generally better to just use
or
where possible. That just leaves things like:
vs
which is still pretty rare, and there’s still a warning for it in the MS C# compiler (and probably in some Java compilers).