patterncsharpMinor
Optimize boolean statements
Viewed 0 times
statementsoptimizeboolean
Problem
I have the following logic:
I believe that there may be a way to minimize this logic (or rewrite it in a more clever way) that I am not thinking of.
bool a;
bool b;
int v = 0;
//code here to set the values of a and b...
if(b)
{
v = a ? 1 : 2;
}
else
{
v = a ? 0 : 1;
}I believe that there may be a way to minimize this logic (or rewrite it in a more clever way) that I am not thinking of.
Solution
int v = b ? (a ? 1 : 2) : (a ? 0 : 1);EDIT #1:
As per svick, parsed out conditional operator on separate lines:
int v = b
? (a ? 1 : 2)
: (a ? 0 : 1);EDIT #2:
Here's one I don't like, but it has no branching whatsoever:
int v = Convert.ToInt32(b) + Convert.ToInt32(!a);Code Snippets
int v = b ? (a ? 1 : 2) : (a ? 0 : 1);int v = b
? (a ? 1 : 2)
: (a ? 0 : 1);int v = Convert.ToInt32(b) + Convert.ToInt32(!a);Context
StackExchange Code Review Q#21130, answer score: 5
Revisions (0)
No revisions yet.