C Switch Statement

I have the following if-statements:

if (strcmp(registerName, "zero")) return 00000; else if (strcmp(registerName, "at")) return 00001; else if (strcmp(registerName, "v0")) return 00010; else if (strcmp(registerName, "v1")) return 00011; 

This is really very long - about 20 if-statements. Therefore, I would like to use a switch. How would I convert this to switch when each operator has a different condition?

I tried something as the code below, but it does not work:

 int registerAddress; switch(registerAddress) { case 1 (strcmp(registerName, "zero")): regsiterAddress = 00000; break; case 2 (strcmp(registerName, "at")): registerAddress = 00001; break; } 
+6
source share
5 answers

You can't - The switch in C work only on primitive types, not strings. You can use, say, a hash table or search tree to optimize compliance, but only for 20 options that may not be worth the trouble.

What you can do to clear the code is the mapping table:

 struct str2Num { char *str; int num; }; const struct str2Num registerMap[] = { { "zero", 00000 }, { "at", 00001 }, { "v0", 00010 }, { "v1", 00011 }, { NULL, 0 } /* end marker */ }; 

and follow these steps:

 int i; for (i = 0; registerMap[i].str != NULL; i++) { if (strcmp(registerName, registerMap[i].str) == 0) { return registerMap[i].num; } } /* handle no-match case here */ 

In fact, if you sorted the table alphabetically, you can even use bsearch() for quick matching.

+8
source

You can only include integers, so this will not work.

If all you do is convert the string to int, store the information in an array and view it.

 struct { const char *name; int value; } fooMapping[] = { {"zero",0}, {"at",1} .... }; int foo2value(const char *name) { size_t i; for(i = 0; i < sizeof fooMapping/sizeof fooMapping[0]; i++) { if(strcmp(name, fooMapping[i].name) == 0) return fooMapping[i].value; } return -1; } 
+7
source

In the switch

 switch(number) { case 1; case 2; case 7; } 

you basically say if number = 1, then case 1. If number = 7, case 7. So you need to assign each text value, in your case "zero" "to" "v0" and "v1", you need will put them in an array, and in the switch statement, instead of switch (number), you must switch an integer that will correspond to the index number of any text that you had. Therefore, if array [3] was = "v0", you must assign an integer to index (3), and then switch (integer). Hope this helps.

+1
source

Why not use? the operator is this:

 return strcmp(registerName, "zero")? 00000: strcmp(registerName, "at") ? 00001: strcmp(registerName, "v0") ? 00010: strcmp(registerName, "v1") ? 00011: ... 
+1
source

Since the switch only works with numbers or single characters, I would use the GNU gperf tool to create a perfect hash and include this value (followed by strcmp () to make sure that it matches exactly). This should give you the desired performance improvement.

0
source

Source: https://habr.com/ru/post/899718/


All Articles