[cfe-dev] discriminating explicit boolean expressions from implicit boolean expressions in the AST

Richard legalize at xmission.com
Tue Mar 31 10:06:40 PDT 2015


In article <CAENS6EsAsF0NYiZkb2x_cbLm2HWH_m73Jd5rkAGGNkZnCLv1tw at mail.gmail.com>,
    David Blaikie <dblaikie at gmail.com> writes:

> On Wed, Mar 25, 2015 at 3:24 PM, Richard <legalize at xmission.com> wrote:

> > AFAIK, all the smart pointer classes have bool conversion operators.
> >
> 
> They do, but they're explicit and my point was "return bool(sp);" is less
> good than "return sp != nullptr;" - so without knowing the domain-specific
> bool test it's probably hard to pick/suggest the best fix.

Exactly.

It is hard to know the best idiom without coding in a giant table that
has to be updated all the time.

In the case of a return statement, you don't need to do anything.

If they wrote 'if (sp != nullptr) return true; else return false;',
then the tool would replace this with 'return sp != nullptr;'.

If they wrote 'if (sp) return true; else return false;', the tool
would replace this with 'return sp;'.

In both cases, the tool assumes that you wrote one or the other based
on your preferences of what is readable and it shouldn't be changed.

It's only in the case of a ternary operator embedded within a larger
expression that you have to do something.  I don't want the tool to subtly
change the type of the expression from bool to something else that is
implicitly convertible to bool but might be interpreted as something
other than bool in the larger context.

However, in the case of a ternary operation, something like:

	foo ^= (p ? true : false);

changing that to:

	foo ^= p;

can introduce errors depending on the type of foo and p.  In these
cases, at the very least the tool should do:

	foo ^= static_cast<bool>(p);

in order to leave the interpretation of the expression unchanged.

At a later date, more heuristics can be added so that the expression
is something more idiomatic than static_cast, but that isn't an issue
of correctness, it's an issue of style and hence subject to all kinds
of varying opinions.

At this point I am only concerned about correctness.
-- 
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
     The Computer Graphics Museum <http://ComputerGraphicsMuseum.org>
         The Terminals Wiki <http://terminals.classiccmp.org>
  Legalize Adulthood! (my blog) <http://LegalizeAdulthood.wordpress.com>



More information about the cfe-dev mailing list