Why Do Some Experienced Programmers Write Comparisons with the Value Before the Variable

Why do some experienced programmers write comparisons with the value before the variable?

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

Why put the constant before the variable in a comparison?

It's a mechanism to avoid mistakes like this:

if ( var = NULL ) {
// ...
}

If you write it with the variable name on the right hand side the compiler will be able catch certain mistakes:

if ( NULL = var ) {  // not legal, won't compile
// ...
}

Of course this won't work if variable names appear on both sides of the equal sign and some people find this style unappealing.

Edit:

As Evan mentioned in the comments, any decent compiler will warn you about this if you enable warnings, for example, gcc -Wall will give you the following:

warning: suggest parentheses around assignment used as truth value

You should always enable warnings on your compiler, it is the cheapest way to find errors.

Lastly, as Mike B points out, this is a matter of style and doesn't affect the performance of the program.

Why do some people put the value before variable in if statement?

They are equivalent.

Some programmers prefer this "Yoda style" in order to avoid the risk of accidentally writing:

if ($variable = true) {
// ...
}

, which is equivalent to

$variable = true;
// ...

, when they meant to write

if ($variable === true) {
// ...
}

(whereas if (true = $variable) would generate an obvious error rather than a potentially-subtle bug).

PHP why (null === $variable) and not ($variable === null) in comparison?

It helps prevent accidental assignments:

if ($foo = null) { ... }

would not cause a parse error, while will

if (null = $foo) { ... }

1st example: http://sandbox.onlinephpfunctions.com/code/fff14c285a18a7972a3222ff5af08da825760c10
2nd example: http://sandbox.onlinephpfunctions.com/code/118d494c17381d8e129ba005465bf84d9b8819bd

Why if( constant == variable ) is preferred instead of if ( variable == constant )

Because that form makes it harder to introduce a bug by forgetting one of the equals signs. Imagine if you did this:

if (k = 5)

This was intended as a comparison, but it's now an assignment! What's worse, it is legal, and it will mess up your program in multiple ways (the value of k is changed, and the conditional always evaluates to true).

Contrast this with

if (5 = k)

This is not legal (you cannot assign to a literal) so the compiler will immediately flag it as an error.

That said, this style of writing code (assignments within conditionals) is not as prevalent today as it once was. Most modern compilers will flag this as a warning, so it's unlikely to go undetected. Personally I don't like the second form and since the compiler is there to help I don't use it.

Is it bad to explicitly compare against boolean constants e.g. if (b == false) in Java?

It's not necessarily bad, it's just superfluous. Also, the actual variable name weights a lot. I would prefer for example if (userIsAllowedToLogin) over if (b) or even worse if (flag).

As to the performance concern, the compiler optimizes it away at any way.

As to the authoritative sources, I can't find something explicitly in the Java Code Conventions as originally written by Sun, but at least Checkstyle has a SimplifyBooleanExpression module which would warn about that.

When is calculating or variable-reading faster?

It will generally always be faster to store something calculated once, rather than calculate it each time, unless the calculation is minor and/or the number of times you use it is low.

In other words, it depends entirely on the usage patterns. Consider, for example, the two extremes below.

  • The calculation is a adding two numbers together and you only use the result twice.
  • The calculation is a monstrous Physics calculation involving the interaction of 47 separate sub-atomic particles, and you use it in three different places in your code, one of which uses it inside a loop with 314,159,265 iterations.

Obviously, you won't get much (or possibly any) benefit from calculating it once in the first example but you're extremely likely to benefit by doing so for the second case.

As a general rule, you should first write your code for functionality and readability, and then only worry about performance if it becomes an issue.

Why does one often see null != variable instead of variable != null in C#?

It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):

// Probably wrong
if (x = 5)

when you actually probably meant

if (x == 5)

You can work around this in C by doing:

if (5 == x)

A typo here will result in invalid code.

Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an "if" statement requires a Boolean expression to start with, and the type of "x=5" is Int32, not Boolean.

I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.

When comparing a variable to a literal, should one place the literal on the left or right of the equals '==' operator?

The reasoning being that if you accidentally type = instead of ==, then the code will fail at compile.

True. On the other hand, I believe modern C and C++ compilers (I'm assuming you're using one of those languages? You haven't said) will warn you if you do this.

Have you tried it with the compiler you're using? If it doesn't do it by default, look to see if there are flags you can use to provoke it - ideally to make it an error rather than just a warning.

For example, using the Microsoft C compiler, I get:

cl /Wall Test.c
test.c(3) : warning C4706: assignment within conditional expression

That's pretty clear, IMO. (The default warning settings don't spot it, admittedly.)

Being unaccustomed to this style, reading 7 == x is difficult for me, slowing my comprehension of their code.

Indeed. Your approach is the more natural style, and should (IMO) be used unless you're really dealing with a compiler which doesn't spot this as a potential problem (and you have no alternative to using that compiler).

EDIT: Note that this isn't a problem in all languages - not even all C-like languages.

For example, although both Java and C# have a similar if construct, the condition expression in both needs to be implicitly convertible to a Boolean value. While the assignment part would compile, the type of the expression in your first example would be int, which isn't implicitly convertible to the relevant Boolean type in either language, leading to a compile-time error. The rare situation where you'd still have a problem would be:

if (foo == true)

which, if typo'd to:

if (foo = true)

would compile and do the wrong thing. The MS C# compiler even warns you about that, although it's generally better to just use

if (foo)

or

if (!foo)

where possible. That just leaves things like:

if (x == MethodReturningBool())

vs

if (MethodReturningBool() == x)

which is still pretty rare, and there's still a warning for it in the MS C# compiler (and probably in some Java compilers).

What does compares less than 0 mean?

What I am interested in, more exactly, is an equivalent expression of "compares <0". Does "compares <0" mean "evaluates to a negative number"?

First, we need to understand the difference between what you quoted and actual wording for the standard. What you quoted was just an explanation for what would actually get put into the standard.

The standard wording in P0515 for the language feature operator<=> is that it returns one of 5 possible types. Those types are defined by the library wording in P0768.

Those types are not integers. Or even enumerations. They are class types. Which means they have exactly and only the operations that the library defines for them. And the library wording is very specific about them:

The comparison category types’ relational and equality friend functions are specified with an anonymous parameter of unspecified type. This type shall be selected by the implementation such that these parameters can accept literal 0
as a corresponding argument. [Example: nullptr_t satisfies this requirement. —
end example] In this context, the behaviour of a program that supplies an argument other than a literal 0 is undefined.

Therefore, Herb's text is translated directly into standard wording: it compares less than 0. No more, no less. Not "is a negative number"; it's a value type where the only thing you can do with it is comparing it to zero.

It's important to note how Herb's descriptive text "compares less than 0" translates to the actual standard text. The standard text in P0515 makes it clear that the result of 1 <=> 2 is strong_order::less. And the standard text in P0768 tells us that strong_order::less < 0 is true.

But it also tells us that all other comparisons are the functional equivalent of the descriptive phrase "compares less than 0".

For example, if -1 "compares less than 0", then that would also imply that it does not compare equal to zero. And that it does not compare greater than 0. It also implies that 0 does not compare less than -1. And so on.

P0768 tells us that the relationship between strong_order::less and the literal 0 fits all of the implications of the words "compares less than 0".



Related Topics



Leave a reply



Submit