简体   繁体   中英

Logical confusion for giving if condition

I want to give a condition in such a way that if all values are either 0 or 1, then some logic is executed.

I have three variables.

   0 0 0 -> evaluates to True
   1 1 1 -> evaluates to True

All other combinations evaluate to False. How can I write the logic for this?

bool condition1, condition2, condition3;
...
if ((condition1 == condition2) && (condition2 == condition3))

or

bool allThreeEqual = (condition1 == condition2) && (condition2 == condition3);

Start by expressing what you're thinking in words as simple code:

int a, b, c;

// ...

bool eval = false; // assume false, prove otherwise

if( (a==0) && (b==0) && (c==0) )
  eval = true;
else if( (a==1) && (b==1) && (c==1) )
  eval = true;

Some would argue that the above is not elegant. I disagree. The above is simple, straightforward, and dumb-simple to understand, maintain and extend. Sounds like the definition of elegant to me.

Once this simple logic has been written, you can evaluate if you need to do performance benchmarking on this code. If you do, and you determine that this is indeed a real bottleneck, then you can mode forward optimizing it, perhaps by leveraging the transitive relationship between the elements. Almost every time however this will be plenty fast enough, and there will be no need to make any changes at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM