Simulater / Generated switch application range in c

Are there any hacks to support the case of a range in the c (99?) Operator or object C switch? I know this is not supported in order to write something like this:

switch(x) case 1: case 2..10: case 11: 

But I thought there should be a way to generate code with the #define macro. Of course I can define a to-do list macro, but I was hoping for a more elegant way, like CASERANGE (x, x + 10), which would generate:

 case x case x+1 case x+2 

Is it possible?

0
c macros c99 objective-c switch-statement
Jan 13 '11 at 13:21
source share
3 answers

GCC has a C extension that allows something similar to your first example, but other than that, if there is a portable / ANSI way to do this, that would be done by now. I do not believe that there is one.

+3
Jan 13 '11 at
source share

Doing this with macros is close or impossible. Compiler extensions exist, but they are specific to the compiler, not cross-platform / standard. There is no standard way to do this, use the / else chains instead.

+2
Jan 13 '11 at 13:29
source share

In modern C (C99, with variable-length macros), this can be accomplished using macros. But you probably would not want to code this completely. P99 provides a set of tools for this. In particular, there is a P99_FOR meta macro that allows you to expand lists of arguments of finite length.

 #define P00_CASE_FL(NAME, X, I) case I: NAME(X); break #define CASES_FL(NAME, ...) P99_FOR(NAME, P99_NARG(__VA_ARGS__), P00_SEQ, P00_CASE_FL, __VA_ARGS__) 

will extend CASES_FL(myFunc, oi, ui, ei) to something like

 case 0: myFunc(oi); break; case 1: myFunc(ui); break; case 2: myFunc(ei); break 

Edit: answer a specific question

 #define P00_CASESEP(NAME, I, X, Y) X:; Y #define P00_CASERANGE(NAME, X, I) case ((NAME)+I) #define P99_CASERANGE(START, LEN) P99_FOR(START, LEN, P00_CASESEP, P00_CASERANGE, P99_REP(LEN,)) 

where P00_CASESEP just ensures that between cases there is P00_CASESEP , and P99_REP generates a list with LEN empty arguments.

Would you use this, for example, as

 switch(i) { P99_CASERANGE('0',10): return i; } 

Observe : after the macro, that it is as close as possible to the usual case syntax, and also that the LEN parameter should expand to a simple decimal number, not an expression or so.

+2
Jan 13 2018-11-22T00:
source share



All Articles