views:

250

answers:

6

EDIT: Found duplicate once I learned the term for this behaviour. Close as duplicate please.

Consider this

Class* p = NULL;
if( p != NULL && p->Method() == OK ){

  // stuff
}

On all compilers I've worked with, this is quite safe. I.e. the first part of the boolean expression will evaluate to false, and the call to Method() will thus not be attempted since evaluating the second part is redundant.

Is this because most compilers will optimize away the evaluation of the second part, or is it a dictated behavior from the C/C++ standards?

EDIT: Found duplicate once I learned the term for this behaviour. Close as duplicate please.

+3  A: 

Expression short cutting is guaranteed by the standard.

Paul Tomblin
+1  A: 

This is a feature called short circuiting. This behavior is guaranteed by the C++ standard. I do not believe it is an optimization so to speak but it's much more of simply a language feature.

JaredPar
+3  A: 

This is called boolean short circuiting and is defined into many languages. Here is a wikipedia article that describes which languages have this feature.

Now that you know the correct name for the feature, there are other SO articles about it as well.

Jack Bolding
+3  A: 

С++ Standard 1998
Section 5.14

The && operator groups left-to-right. The operands are both implicitly converted to type bool(clause 4). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.

Mykola Golubyev
Which standard? We've got C and C++ standards that guarantee that, not to mention numerous other languages, and two versions of the C standard (not that something this basic is likely to have changed in position).
David Thornley
+1  A: 

I haven't seen it mentioned yet, so:

Short-circuiting is guaranteed by C++ except when the && or || operator being invoked is overloaded. But don't do that, because it's too confusing.

j_random_hacker
+1  A: 

It's not just optimization, it's useful to let you be more concise.

As your example shows, it lets you write a "safe" dereferencing statement in one line. Otherwise, you have to do something like:

if (p != null) {
    if (p.getValue() == 3) {
        // do stuff
    }
}

Seems trivial, but try coding in a language that doesn't have it (e.g. VB6) and you begin to sorely miss it.

It's in the language standards as other answers mention, but only because something like this needs to be clearly specified. That it can possibly compile down to optimized code is a side-effect; these days, a decent C or C++ compiler would compile the one-line or two-line statements equivilently

Matt