I'm looking through some code and I found some strange conditionals, namely:
if (NULL != buf) {...}
I was wondering if there was a particular reason for writing the conditional like this, instead of
if(buf != NULL){...}
I can't see any reason to do it the first way off the top of my head, but I don't think it was a mistake. To me, it seems like they accomplish the same thing, but the second way is way more intuitive. Is there some specific reason to use the first conditional?
Yes, it's called "Yoda conditions". The idea is to not accidentally assign a value when you mean to be doing a check. Most modern compilers should catch it.
It is to avoid newbie typo like if (buf = NULL).
if (NULL = buf) leads to compilation error, while if (buf = NULL) is totally correct with undesired semantic.
The concept is basically this:
Often new learners miss the double equals sign == and use a single = instead. Instructors therefore teach them this method so that they are not stuck at simple programs.
With no compiler warnings enabled, if you do this:
if(buf = NULL)
You are basically assigning NULL to buf, which is not syntactically wrong, and you would not get any warnings, but when you do this:
if(NULL = buf)
the compiler throws error because it knows you cannot assign anything to NULL.
Why Yoda in particular?
It's because of the character Yoda, from Star Wars, whose dialogues were styled in reverse orders, like " Blue is the sky".
You can read more interesting coding terms here.