Would this use of struct and function references be considered okay?

Would this code be considered valid? It obviously works but could it be improved? If so, how?

The purpose of this is to replace a giant block of if.... else if.... else if statements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#if _MY_PROGRAM_DEBUG_LEVEL >= 1
#include <iostream>
#endif // 

void test_func_ref();

struct transition_table
{
	char trans_key_1;
	char trans_key_2;
	void(&func_ref)();
};

int main() {

	transition_table test_table[] = {
		{ 'A','B', test_func_ref },
		{ 'B','Q', test_func_ref },
		{ 'D','S', test_func_ref },
		{ 'E','Q', test_func_ref },
		{ 'B','W', test_func_ref },
		{ 'F','Q', test_func_ref },
		{ 'B','S', test_func_ref },
		{ 'S','Q', test_func_ref },
		{ 'B','X', test_func_ref },
		{ 'R','R', test_func_ref },
		{ 'B','O', test_func_ref },
		{ 'K','Q', test_func_ref },
		{ 'J','I', test_func_ref }
	};

	char choice1,choice2;

	std::cin >> choice1 >> choice2;

	for (int i = 0; i < (sizeof(test_table) / sizeof(test_table[0])); i++) {
		if (choice1 == test_table[i].trans_key_1)
			if (choice2 == test_table[i].trans_key_2) {
				//Code here
				std::cout << std::endl;
				std::cout << "This is equal to table row " << i << std::endl;
				test_table[i].func_ref();
			}
	}

	system("pause");
	return 0;
}

void test_func_ref() {
	std::cout << "Voided function called" << std::endl;
}
It is not only okay, it is brilliant.

(I have tried, without success, to get people to think like this in the past. It is the most efficient, most correct way to do things that I can think of.)

All your lookup code needs to do is to find the lookup item (or fail) and call the handler. That is very, very fast; very, very modular; and very, very easy to maintain.

Good job!
Thank you very much for the feedback!!
Topic archived. No new replies allowed.