Is it possible to get the number of cases in a switch case in C without manually adding a counter variable which is incremented in each case?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
This is horrible, but if you are under gcc you can use the COUNTER macro:
Output:
As I commented earlier, I think you want a dispatch table rather than a switch statement. Here's a little example.
Say you got this:
Now this ca be rewritten to this:
This is usually a much better way than using switch statements. Not only does it make it simpler to add more cases, but it also allows counting of cases. If you have a huge table and sparse cases you can use a hash table instead of a plain array.
EDIT: Of course there are even more advantages with the dispatch table than the switch case, as you can add and remove and change the dispatch table dynamically. That may be the greatest advantage.
(I hope you are on Linux and using a recent GCC compiler)
If you want to count the actual number of cases as seen by the compiler (think of case ranges), you need to know the compiler internal representations, and you could, if compiling with a recent GCC, customize your compiler using GCC MELT and coding our own MELT extension.
BTW, the complexity or efficiency of a
switch
statement is not only (or mostly) related to the number of cases (since the distribution of cases matters a big lot). See the references here.Perhaps you might simply use the
findgimple
mode of GCC MELT to findswitch
gimple statements which are wide enough.Maybe you want computed gotos for threaded code...