Backward Conventions in C

I am looking through the code and I found some strange conditional expressions, namely:

if (NULL != buf) {...}

I was wondering if there was any specific reason for writing a conditional expression, not

if(buf != NULL){...}

I see no reason to do it the first way from my head, but I don’t think it was a mistake. It seems to me that they are doing the same thing, but the second way is more intuitive. Is there any specific reason for using the first conditional?

+4
source share
4 answers

Yes, it's called the " Yoda terms ." The idea is not to randomly assign a value when you want to check. Most modern compilers should catch them.

+7

, if (buf = NULL).

if (NULL = buf) , if (buf = NULL) .

+4

:

== =. , .

, :

if(buf = NULL)

NULL buf, , , :

if(NULL = buf)

, , - NULL.

?

- , " ", , " - ".

.

+3

This will give a compiler error if the comparison expression is incorrectly entered as an assignment expression.

For example, if you compile

if (buf = NULL) {}

the compiler says

warning: suggest parentheses around an assignment used as a true value [-Wparentheses]

but if you change it to

if (NULL = buf) {}

the compiler now says

error: lvalue required as left assignment operand

+2
source

All Articles