Click here to Skip to main content
15,882,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a big if statement that I turned into a switch, unfortunately I find the switch getting too big. I looked at the hash and map but it's beyond ne at this point. Ideally I would like to store all of this in a header file and just call it from there. Just a piece of the switch. Thank you.

switch (ipsrc) {
	Source =;
	Source =;
	case to;
	Source =;
Code-o-mat 2-Oct-11 15:32pm    
And what is your question?
Member 7766180 2-Oct-11 15:37pm    
What else can I do besides having a switch statement with a hundred entries?
Thank you.

1 solution

It seems that what you want here is set the source variable dependent on an IP address.
You want to avoid a big switch statement in code. Correct me if I'm wrong.

I usually handle these kind of cases with a database table that has the cases I need and the value that goes with it.

ID     IPFrom        IPTo          Source

Then write a piece of code (or an SP) that checks if the IP (ipsrc) is between any of the IPFrom and IPTo and get the correct Source value for it. Possibly IPTo could be NULL for the first two rows (whatever you like, it's your design).
The upside is that you do not have a huge switch statement and also that if IP addresses change or get added all you have to do is change or add an IP range to your database table.

Hopefully this is any use to you :)
Share this answer
Member 7766180 2-Oct-11 17:47pm    
This is EXACTLY! what I want. Are there any samples of this method anywhere? What is this called? Thank you!
Philippe Mori 2-Oct-11 21:12pm    
Using a map or STL lower_bound algorithm on a table in code similar to the one above would be in my opinion the easiest way... but if you don't know how to use a map, it would be hard to explain.

If the table is relatively small then a simple loop might be adequate and easier to understand amnd implement.
Member 7766180 3-Oct-11 16:49pm    
Good example here!
Thank you.
Sander Rossel 3-Oct-11 2:15am    
I don't know what it's called, but Philippe Mori calls it "a map or STL lower_bound algorithm" right here, so you might want to Google that up. I also don't have any samples, but it's really just looking up a row with a specific value in a database. The hardest part is comparing IP addresses, which obviously aren't simply integers. But there's probably something on that somewhere on Google too ;)
Good luck and thanks for accepting my answer! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900