Hacker News new | ask | show | jobs
by James_Duval 4655 days ago
Thanks for this.

I don't actually use C, although I know a few languages with C-like syntax (Java, JS, AS2.0) and I'm learning Go & planning to learn D.

This small change will be really helpful in all these languages. Even if I never make this error again it will help stop people who alter my code from making this error.

Perhaps they should teach it in more programming textbooks, as I've not come across it in anything from HeadFirst to online tutorials to Deitel & Deitel.

2 comments

FYI, sometimes called "Yoda condition". I _think_ I was taught to do this when I learnt C (~20 years ago). Wikipedia indicates that the name at least has been around since 2005.
It's not necessary in Java (though it's still a common habit). Assignment to a non-boolean is impossible in an if statement in Java, and you can make the compiler warn you about accidental assignments.
Still, assigning a boolean rather than comparing it is still possible and, possibly, a source of bugs.