views:

55

answers:

2

I'm a seasoned programmer and therefore feel a little embarrassed asking this question but decided to do so anyways.

I'm reading this book, and have also seen various examples across the net where the order of arguments in a compare operation is reversed and I wonder if there is a reason for it, or just because it looks "cool" and does the exact same thing.

Example:

I would code:

if(bool_variable == YES)

while I saw in this book and in various examples

if(YES == bool_variable)

Explanations?

Thanks a ton!

+6  A: 

Some people like yoda conditions because they can help you find errors where you accidentally type = instead of ==. For example:

if (var = YES)

will compile but probably not work the way you want it to. Writing it the other way around:

if (YES = var)

will cause a compile-time error. I personally dislike this construct, but to each his own, I guess.

Carl Norum
And there's no longer any need to do this sort of thing with a modern compiler that can warn when you make that mistake. Both GCC and Clang have this ability.
Peter Hosey
+1 @Peter. `suggest parentheses around assignment in conditional` or something along those lines, I think.
Carl Norum
Thank you very much for enlightening me!
schone
A: 

Carl's got it -- a programmer who puts a constant on the left side will be protected by the compiler.

I just wanted to add that perhaps one of the reasons people switch them around is that one or one's employer may have code style guidelines that specify which side the constant should be on, but of course this just lends itself to the safety net of syntax errors.

I personally have always put the constant on the ride hand side for readability, but to each his/her own.

Cory Larson