C++ Long switch statement or look up with a map?

Personally, I would use the map, as its use implies a data lookup – using a switch usually indicates a difference in program behavior. Furthermore modifying the data mapping is easier with a map than with a switch.

If performance is a real issue, profiling is the only way to get a usable answer. A switch may not be faster if branch mispredictions happen often enough.

Another approach to think about this is if it wouldn’t make more sense to combine the code and the associated value into a datastructure, especially if the range of codes and values is static:

struct Code { int code; int value; };

Code c = ...

std::cout << "Code " << c.code << ", value " << c.value << std::end;

Leave a Comment