c++ - Lazy logic and temporary values to improve the reading of an expression -


sorry poor explanatory title, i'm not able find better 1 (yet).

i'm used code boolean expressions adding temporary variables improve reading of expression, in other words dislike this:

// example 1 // hard read , understand @ first glance if (value % 2 && value ^ weirdflags &&     (value > threshold) && (value < ceiling) &&     /* lots of comparisions */) { /* something*/ } 

and prefer this:

// example 2 // way easier read , understand const bool iseven = value % 2; const bool flagschecked = value ^ weirdflags; const bool inrange = (value > threshold) && (value < ceiling); const bool foo = /* lots of comparisions */; if (iseven && flagschecked && inrange && foo) { /* something*/ } 

but using favorite coding style, i'm not taking advantage of lazy logic optimizations because temporary values computed, while other coding style imprescindible computed.

there's solution, grants use of lazy logic optimizations , keeps code readable, comment code:

// example 3 // check test if value number // , checks value provided flags // , assures value in required range // , lots of additional comparisions if (value % 2 && value ^ weirdflags &&     (value > threshold) && (value < ceiling) &&     /* lots of comparisions */) { /* something*/ } 

but there's no warranties code comments matches code below during code development while team of programmers coding day day same source file (not coders care documentation). that's why preffer code explains in neat way.

so, finally, studying example 2 case, declares temporary values const, use them in boolean expression, in same scope of expression , close expression itself, questions are:

  • in example 2, compiler perform kind of optimizations involving temporary values in order improve performance of boolean expression (lazy evaluation)?
  • in own opinion, of 3 examples correct? why?

thanks advice.

check out:

if(const bool iseven = value % 2) if(const bool flagschecked = value ^ weirdflags) if(const bool inrange = (value > threshold) && (value < ceiling)) if(const bool foo = /* lots of comparisions */) {     /* something*/ } 

magic!


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -