3

I have seen a few examples lately where if statements are written as follows:

if ( false === $testValue) {
    //do something
}

as opposed to the more general:

if ($testValue === false) {
    //do something
}

Clearly it is a style issue and it has no bearing on the result, but my question is can anyone say why anyone would use this style and where it comes from.

The code examples I have seen with this style have been from seriously good programmers so I dont think its a necessarily a bad style.

David
  • 93
  • 1
  • 4
  • possible duplicate of [Why does one often see "null != variable" instead of "variable != null" in C#?](http://stackoverflow.com/questions/271561/why-does-one-often-see-null-variable-instead-of-variable-null-in-c) – Brian Roach Apr 03 '11 at 15:33
  • Related http://stackoverflow.com/q/1264781/38206 – Brian Rasmussen Apr 03 '11 at 15:48

4 Answers4

6

It's so that if you accidentally type = (assignment) instead of == (comparison), the compiler complains that the constant cannot be assigned to.

Compare:

if (false = $testValue) {
    // does not compile, cannot assign to constant
}

to:

if ($testValue = false) {
    // assigns false to $testValue, never evaluates to true
}

The former doesn't compile, the latter does and has a bug.

Core Xii
  • 6,270
  • 4
  • 31
  • 42
  • 1
    however in `.net` **Second one also not get compiled** – Waqas Raja Apr 03 '11 at 15:40
  • Great thank you. I knew there was a reason for it but just couldnt think what it would be. I develop in php so this really isnt an issue for me. – David Apr 03 '11 at 15:44
0

I used to see checks like this in C and C++:

if (null == x)

The reason for it was that mistyping = for == would make no sense to the compiler, because assignment to null or a constant would be an error.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

In something like C++ (I'm not sure what language you're using there with the ===) if you have

if(x == 2), and you write it if(x=2) (so the value is assigned an not checked for equality) this doesn't cause a compiler error (most compilers today will warn you about it), but if you write if (2=x) instead of if(2==x) that will defintely produce an error.

jonsca
  • 10,218
  • 26
  • 54
  • 62
0

It's to prevent assignment when comparison was intended. I don't like this style myself but I see it a lot from our Indian developers so maybe it's being taught over there.

It's completely unnecessary if a '0 warnings, 0 errors' build policy was adhered to, and anyone who uses this style is not likely to provide clean building code.

James
  • 9,064
  • 3
  • 31
  • 49