+2  A: 

It avoids that you write var = NULL. Writing NULL = var will yield an error. So you're right :-)

Scharron
+18  A: 

Yes, that's correct. It's to detect the typo of = instead of ==.

mdma
+6  A: 

its because you cannot assign a value to a constant, so if by mistake you put = instead of == the compiler throws an error, alerting you

Necrolis
+21  A: 

That used to be the case, yes. Of course, nowadays almost all compilers warn about assignments in if() conditions, so the advantage is only there for people who routinely suppress warnings.

Kilian Foth
And suppressing warnings will lead to far bigger problems than accidental assignments.
Mike Seymour
When most coding standards now say make warnings errors so the code will always compile clean. This is just consider old style (and on a personal note I find it slightly harder to read as it is not a natural way to think of things).
Martin York
I wonder if g++ has such warnings? I don't suppress warnings, and I've never gotten one for assignments in conditionals.
Peter Ajtai
@Peter: yes, but warnings are suppressed by default. You have to enable this warning with `-Wparentheses` or `-Wall`. I'd recommend always compiling with `-Wall -Wextra`.
Mike Seymour
@Mike - Thanks!
Peter Ajtai
+4  A: 

That is a common justification, as is the argument that you don't want to push the constant off to the far right of the screen with a long-winded expression. The latter argument has never sounded particularly convincing to me, and the former isn't really valid these days, since any self-respecting compiler will issue warnings (you do compile with warnings-as-errors, don't you? :-).

EDIT: I just came across the new Xcode 4 preview, and just look at the example they chose to exemplify their new "Fix-it" feature!

alt text

Marcelo Cantos
I hate warnings-as-errors! arrrg!
Gianni
@Gianni: Why exactly ?
ereOn
It breaks my code, all too often, for stupid/silly reasons. Sure, having code that compiles without any warnings is desirable, but not necessary. I should be better at knowing what the code should look like, and what warnings I can live with, than the compiler. Besides, sometimes I put in #warning myself to remind me of something that should be changed or re-factored in the future.
Gianni
Example: a main-loop asserts if it makes it past the }. The function return type is int and the compiler warns about it. So now I have to go while (TRUE) {// do stuff} assert(FALSE); return 0; which is just another pointless compile iteration. Sure I'll fix it, but I don't want my build to stop because of it.
Nathon
There's a difference between constructs that are questionable in some circumstances and constructs that are almost certainly bugs. Unfortunately, this isn't normally the difference between warnings and errors. It would be useful to be able to specify that some warnings are errors and some aren't.
David Thornley
@Nathon: for some compilers (gcc and MSVC, at least), you can hint that a function will not be returning, which would eliminate that warning
Hasturkun
Especially "“warning C4800: ‘int’ : forcing value to bool ‘true’ or ‘false’ (performance warning)" which a) isn't and b) is their fault for defining BOOL as an int
Martin Beckett
@Martin, @Gianni, @Nathon: Yes there are cases where the compiler is overly-cautious, (AFAIK, gcc doesn't emit a warning like C4800, only MSVC). But such protestations do not justify a policy of letting warnings accumulate freely. @Nathon, in particular: "Sure I'll fix it," is a refrain I've heard often, and all too often followed several months later by, "Oh crap, I meant to fix that!" after a two-day bug-hunting expedition. This is classic "boiled-frog" mentality; once you reach 100 warnings per build, it's just too hard to spot real problems.
Marcelo Cantos
I (constant==expression) because 1) I have been caught out before and 2) I don;'t trust warnings to protect me. Another reason is this DOESN'T generate a warning - so you can use this and have a no-warniggs policy.
Martin Beckett
@Martin: You need to turn on the appropriate warning levels. `cc -Wall -Werror prog.c` => `error: suggest parentheses around assignment used as truth value`
Marcelo Cantos
Well, in my defense, my code currently does build with no warnings. I just don't like being forced to clear them out while I'm debugging or developing a new feature.
Nathon
@Martin: MSVC is in general bad about giving warnings about things that are *Microsoft's* fault. Like C4786 about debug symbols being longer than 255 characters.
dan04
+3  A: 

To catch the difference between assigning and comparing.

If you mean:

if (ptr == foo)

but type

if (ptr = foo)

if will still be valid code, since ptr = foo will evaluate to a boolean check on ptr after it has been set to the value of foo. Obviously, you don't want this.

However, I find it hurts readability considerably, and given that most IDE's and preprocessors will catch this anyway, never use this style.

davbryn
A: 

As a java developer I tend to write expressions like this:

   //primitive check
   if(constant == variable)

   //Object check
   if(constant.equals(variable))

This is particularly important for the object because the expression doesn't error if the variable is null. If the expression were in the other order, a null variable would error. I maintain consistency and do the same order for primitives.

Jay
I think he was talking about C++ if you could provide an example in that context instead.
0A0D
Wow, getting down voted for adding some extra information, rough, real rough.
Jay
You're not being down-voted for adding extra information, you're being down-voted for adding irrelevant information. This question isn't about Java.
GMan
But it is object orientated way of thinking, which is on topic to this question.
Jay
+2  A: 

Check out the top-rated answer to this question..

http://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined

They've dubbed this coding style "Yoda Conditions".

C.McAtackney
+4  A: 

This has been dubbed as a "Yoda Conditional"!!!

See here http://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined

I really like that term because:

if(Light::On == light)

Reads as:

"If on is the light"

As stated already, this is used to prevent incorrect assignment. It could be argued that this practice is archaic based on modern IDEs but I still think it is good practice.

David Relihan
+1  A: 

Catching assignment is a major reason Yoda conditions are used, but there are others: In C++ the operator is invoked on the LHS operand. As constants are typically const (duh), or primitives, this limits the possibility of non-sensical operations. One example is = on a primitive literal, such as the common reason given (1 = a), but this will include operator=() const, or whatever operator is used for non-POD types.

Matt Joiner
+1  A: 

With a language such as VB 6.0 which does not not have distinct assignment and comparison operators,

a = 2

' Will compile, whether you mean a is assigned 2 or whether you are comparing a with 2 If you meant compare, there is a likelihood that a runtime error ensues.

' For Assignment if you always write

a = 2

' And for Assignment if you always write

2 = a

' You eliminate the Compile-success and runtime-error scenario.

But, this is just the tip: the visual hint is unavailable when you have an expression like

a = b ' Comparison or assignment?

C# has: - different assignment (=) & comparison (==) symbols - comparisons have to be wrapped in brackets.

Then this becomes a non-issue.

AAsk
A: 

Because they know what they're doing :P

StudiousJoseph
A: 

You're right - it's to trigger a compiler error if you mistype "==" as "=", since an assignment will always return true. While this will usually be easy to notice and debug, once in a while it will turn into a very hard to detect bug, think of this:

#define OK 2 // Or something...
[...]
while(status = OK){
    // This loop will never end
    // Even if you change the value of status within it
    [...]
}

That can be a nasty bug to find, especially if the block belonging to the offending statement is long (imagine looking for all the possible reasons why status is always staying OK).

If on the other hand you used:

while(OK = status){

That would throw a compiler error, since you cannot assign a value to a constant.

This practice is sometimes referred to as Yoda conditions, since it juxtaposes the object and subject. Like "if status is OK" vs "if OK is status" and "the sky is blue" vs "blue is the sky" - the latter being something Yoda might say.

btfx