Search code examples
c++cstandards-complianceboolean-logicboolean-expression

Is "boolean short circuiting" dictated by standard or just mostly used as optimization?


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?


Solution

  • 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.