Matthew D. Scholefield
Matthew D. Scholefield

Reputation: 3336

More Efficient way to code if then else statements in c++

I'm coding in c++ for the Nintendo DS, but this should be universal with all c++.

I already know about switch statements, but I need to make a set of if, then, and else that have multiple arguments:

void doSomething(int number)
{
...
}

bool left = true;
bool right = false;
bool top = false;
bool bottom = false;

if (left && top && right)
    doSomething(1);
else if (top && right && bottom)
    doSomething(2);
else if (left && right && bottom)
    doSomething(3);
else if (left && top && bottom)
    doSomething(4);

Any help is appreciated.

Upvotes: 2

Views: 2279

Answers (4)

Escualo
Escualo

Reputation: 42072

I am adding this response just to show how can a std::bitset could be used for this purpose. I am aware that maybe your target platform will not support the C++11 Standard, but hopefully this can help someone else.

#include<iostream>
#include<bitset>
#include<vector>
#include<map>

// The location is represented as a set of four bits; we also need a
// comparator so that we can later store them in a map.
using Location = std::bitset<4>;
struct LocationComparator {
  bool operator()(const Location& loc1, const Location& loc2) const {
    return loc1.to_ulong() < loc2.to_ulong();
  }
};

// the callback (handler) has a signature "void callback()"
using Callback = void (*)( );

// the mapping between location and callback is stored in a simple
// std::map
using CallbackMap = std::map<Location, Callback, LocationComparator>;

// we define the fundamental locations
const Location Top   ("1000");
const Location Bottom("0100");
const Location Right ("0010");
const Location Left  ("0001");

// ... and define some actions (notice the signature corresponds to
// Callback)
void action_1() { std::cout<<"action 1"<<std::endl;}
void action_2() { std::cout<<"action 2"<<std::endl;}
void action_3() { std::cout<<"action 3"<<std::endl;}
void action_4() { std::cout<<"action 4"<<std::endl;}

// ... now create the map between specific locations and actions
// (notice that bitset can perform logical operations)
CallbackMap callbacks = {
  { Top    | Right , action_1 },
  { Top    | Left  , action_2 },
  { Bottom | Right , action_3 },
  { Bottom | Left  , action_4 },
};

// an abstract game element has a location, the interaction will
// depend on the defined callbacks
class GameElement {
 public:
  GameElement(const Location& location)
      : m_location(location) { }

  void interact() const {
    callbacks[m_location]();
  }

  virtual ~GameElement() { } // so that others can inherit
 private:
  Location m_location;
};

int main() {
  // create a vector of game elements and make them interact according
  // to their positions

  std::vector<GameElement> elements;

  elements.emplace_back(Top    | Right);
  elements.emplace_back(Top    | Left);
  elements.emplace_back(Bottom | Right);
  elements.emplace_back(Bottom | Left);

  for(auto & e : elements) {
    e.interact();
  }

}

I compiled it on OS X using GCC 4.7.2 using the following command:

g++ locations.cpp -std=c++11

The output is:

action 1
action 2
action 3
action 4

Upvotes: 0

Kyle_the_hacker
Kyle_the_hacker

Reputation: 1434

If you are really a psycho (or obfuscator), you could use something like bitmasks:

unsigned char direction = 8;  // 1 0 0 0  for  l r t b

or by staying consistent with the convention you used in your question:

unsigned char direction = left + (right << 1) + (top << 2) + (bottom << 3);

and then you will have (*):

switch(direction) {
    case 14:  // 1 1 1 0
        doSomething(1);
        break;
    case 7:  // 0 1 1 1
        doSomething(2);
        break;
    case 13:  // 1 1 0 1
        doSomething(3);
        break;
    case 11:  // 1 0 1 1
        doSomething(4);
        break;
}

And if you need to access the individual value conveniently:

inline bool left() {return (direction & 8) == 8;}
inline bool right() {return (direction & 4) == 4;}
inline bool top() {return (direction & 2) == 2;}
inline bool bottom() {return (direction & 1) == 1;}

Actually, this should be pretty fast...


(*) As an alternative, you could also write:

const unsigned char left_c = 8;
const unsigned char right_c = 4;
const unsigned char top_c = 2;
const unsigned char bottom_c = 1;

And test the combination like this (constant-expression are accepted in switches):

switch(direction) {
    case (left_c + right_c + top_c):
        doSomething(1);
        break;
    ...
}

Upvotes: 1

Tarik
Tarik

Reputation: 11209

Encapsulate this into a getSide () that returns an enum. I assume that the boolean variables are accessible from the class implementing or calling doSomething

    ...
    bool left = true;
    bool right = false;
    bool top = false;
    bool bottom = false;
    ...
    doSomething(getSide());
    ...

    enum Side {
    Top, Bottom,  Left, Right
    }

    void doSomething(Side side)
    {
    ...
    }

    Side getSide () {
    if (left && top && right) //Bottom Border
        return Side.Bottom;
    else if (top && right && bottom) //Left Border
        return Side.Left;
    else if (left && right && bottom) //Top Border
        return Side.Top;
    else if (left && top && bottom) //Right Border
        return Side.Right;
    }

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You can convert the four booleans into a binary number 0..15, and use an array to look up the parameter, like this:

int location = (left   ? 1<<0 : 0)
             | (right  ? 1<<1 : 0)
             | (top    ? 1<<2 : 0)
             | (bottom ? 1<<3 : 0);

Now location has a number from 0 to 15, so you can do this:

int lookup[] = {-1, -1, -1, -1, -1, -1, -1,  1, -1, -1, -1, 3, -1, 4, 2, -1};
int arg = lookup[location];
if (arg != -1) {
    doSomething(arg);
}

Upvotes: 10

Related Questions