4

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?

Justin Wang
  • 109
  • 1
  • 7

4 Answers4

7

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.

rost0031
  • 1,894
  • 12
  • 21
4

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.

timrau
  • 22,578
  • 4
  • 51
  • 64
  • 2
    With compiler warning enabled `if (buf = NULL)` would trigger a _Using the result of an assignment as a truth value is recommended with explicit parentheses_ or something like that. – Iharob Al Asimi Jun 30 '15 at 16:39
3

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.

Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43
2

This will give a compiler error if comparison expression is mis typed as assignment expression.

For example, if you compile

if (buf = NULL) {}

the compiler says,

warning: suggest parentheses around assignment used as truth value [-Wparentheses]

but if you change it to

if (NULL = buf) {}

the compiler now says,

error: lvalue required as left operand of assignment

Shreevardhan
  • 12,233
  • 3
  • 36
  • 50