Jump to content
  • Advertisement
Sign in to follow this  
justcallmedrago

Redundant code in switch statement

This topic is 3791 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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:
	switch(letter)
	{
		case 'A':
			value = FREQ_A;
			break;
		case 'B':
			value = FREQ_B;
			break;
	}

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
Advertisement

const int numItems = 3;
int values[numItems ] = {FREQ_A, FREQ_B, ...}
int offset = letter - 'A';
if( offset >= 0 && offset < numItems )
value = values[offset]


[Edit]Wow, three replies in one minute ;)

Share this post


Link to post
Share on other sites
Quote:
Original post by justcallmedrago
Quote:
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 (x.xxx 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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!