Is there a better way to check these two variables instead of four ifs?

Viewed 104

There must be two variables for example A and B, these two will either take the values 0 0, 0 1 , 1 0 or 1 1. I need to check these two variables and return a value between 0 to 3, is there a better way to this than doing four if statements like:

if(B == 0 && A == 0){
  return 0;
}
if(B == 0 && A == 1){
  return 1;
}
if(B == 1 && A == 0){
  return 2;
}
if(B ==1 && A == 1){
  return 3;
}
2 Answers

The four conditions you have shown could be addressed with the single line:

return A + B * 2;

That is, of course, if the A and B values will never be anything other than 0 or 1.

@AdrianMole has already posted the obvious answer for this particular situation. But a more general solution could look like this:

const int ret[2][2] = {
    { 0, 1, },
    { 2, 3, },
};

return ret[B][A];

Not as clean as in the other answer but much cleaner than a bunch of if statements.

Related