Sign in to follow this  

Redundant code in switch statement

Recommended Posts

I have a switch statement that checks a char and assigns a certain value to value Here is the code for the first two letters:
		case 'A':
			value = FREQ_A;
		case 'B':
			value = FREQ_B;

Is there another way that doesn't require 26 total case statements, one for each letter?

Share this post

Link to post
Share on other sites
Original post by justcallmedrago
Original post by SiCrane
Yes. However, the best way to do this depends on the nature of the FREQ_* values.

They are random float values ( to be exact.)
If the 'key' values are contiguous, you can use an array that maps keys to values. Whether or not they are contiguous, you can use a map (e.g. std::map).

In your example, the keys appear to be contiguous integers. However, I'd probably use a map anyway, as it makes fewer assumptions about the input values, and avoids the trouble of computing the proper indices.

Using a map along with the Boost Assignment library, it might look something like this:

#include <map>
#include <boost/assign/list_of.hpp>

// ...

typedef std::map<char, float> map_t;

map_t my_map = boost::assign::map_list_of
('A', 1.f)('B', 2.f)('C', 3.f) /* and so on */;

// ...

value = my_map[some_char];

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this