0

I have observed that a lot of coders while writing a condition statement do something like this

if(NULL == Ptr){

//Some code

}

instead of if(Ptr == NULL){ //some code ...

What is a reason behind this coding practice? I belive that it does not change the meaning of the statement in anyway, so why write like this?

Please point me out if I am making a blunder.

Steve H
  • 461
  • 2
  • 10
  • 18

3 Answers3

4

The usual reason for doing this, is so if the code is mistakenly written as

if(NULL = Ptr){

//Some code

}

It will be a compile error, rather than just a semantic error.

As ouah and Bo Persson point out, this is largely unnecessary, as modern compilers have reintegrated much of the semantic checking that historically was delegated to a separate lint program.

gcc -Wall -Wextra will tell you the line looks fishy:

test.c:3:2: warning: suggest parentheses around assignment used as truth value

I don't consider it semantically wrong as ouah does, comparison being commutative (even when implemented by subtraction and test for non-zero). But it does make the code less readable, if you intend to read it aloud, perhaps to a review group.

If NULL is-equal-to pointer then 
    Block comment (some code) end-Block

It reads funny this way. Whereas

If pointer is-equal-to NULL ...

is smoother to the ear.

luser droog
  • 18,988
  • 3
  • 53
  • 105
  • 1
    The thing is that the compiler will tell you about the problem either way (unlike some compilers from the 1980's). – Bo Persson Apr 13 '13 at 00:40
  • Thanks guys. I appreciate that. Sorry for the duplication of the question. But honestly I dint find it in my search. – Steve H Apr 13 '13 at 05:47
2
if(NULL == Ptr)

is equivalent to

if(Ptr == NULL)

as the == operator is commutative. The idea of this form is to trigger a compiler error if the programmer incorrectly wrote NULL = Ptr when he meant NULL == Ptr.

The problem with this approach is IMHO it makes the code less readable and it is semantically incorrect because you want to compare Ptr to NULL and not the opposite.

Moreover any decent compiler with warnings enabled will trigger a warning with if (Ptr = NULL).

ouah
  • 142,963
  • 15
  • 272
  • 331
0

It does the same thing, but I find it confusing, since to be consistent, you also need to write

 if (0 > a) 

instead of

 if (a < 0)

which is often confusing, since there is a document or something describing that "a must be less than zero", not "zero must be more than a".

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227