Evaluation order question ...

  • Thread starter Thread starter Jamie Risk
  • Start date Start date
J

Jamie Risk

Is this valid?

byte ptr[];
...
if (null != ptr && ptr.Length > 0) {
...
}

(It would be in C)
Or should I break it apart:

if (null != ptr) {
if (ptr.Length > 0) {
...
}
}
 
Jamie said:
Is this valid?

byte ptr[];
...
if (null != ptr && ptr.Length > 0) {
...
}

This is fine as the expression is evaluated left to right in C# and the if
will be exited when the first condition is found that evaluates to false.
So if your ptr is null, the ptr.Length code will never execute.
(It would be in C)
Or should I break it apart:

if (null != ptr) {
if (ptr.Length > 0) {
...
}
}

You can do it this way if you like, but it isn't necessary.
 
Yes, C# will short-circuit that if the first condition is false. That is
part of the C# spec and every compiler should honor that. I believe in the
C/C++ world, that sort of thing is up to the compiler vendor. In C# you can
count on it being there (unless you have a nonstandard compiler vendor).

A side note: you should write ptr != null instead of the other way around.
It reads better to someone looking at your code. All the reasons you did it
the other way around in C are no longer valid in C#.
 
Hi Jamie,

They do the same thing, but I prefer the first one because it fits nicely on
one line. BTW, it's more common in C# to write it as follows:

if (ptr != null && ptr.Length > 0)
{
...
}

The compiler prevents accidental assignment to ptr because it requires the
expression to evaluate to a boolean, not byte[].
 
Yes, C# will short-circuit that if the first condition is false. That is
part of the C# spec and every compiler should honor that. I believe in
the
C/C++ world, that sort of thing is up to the compiler vendor.

Short-circuit evaluation is also required by the language definition in C
and C++ and always has been. It was just another delight for me when moving
from BASIC and Pascal.

///ark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top