Public Group

# Redundant code in switch statement

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

## 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 on other sites
Yes. However, the best way to do this depends on the nature of the FREQ_* values.

'A' - 'A' == 0
'B' - 'A' == 1
'C' - 'A' == 2
and so on.

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

Wow, three replies in one minute ;)

##### Share on other sites
Quote:
 Original post by SiCraneYes. 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.)

##### Share on other sites
Quote:
Original post by justcallmedrago
Quote:
 Original post by SiCraneYes. 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];

1. 1
2. 2
3. 3
4. 4
Rutin
14
5. 5

• 10
• 11
• 9
• 14
• 10
• ### Forum Statistics

• Total Topics
632652
• Total Posts
3007661
• ### Who's Online (See full list)

There are no registered users currently online

×