-2

Having this code:

// Called when x is "a"
#define do(x) doA()

// Called when x is "b"
#define do(x) doB()

Is it possible to make the preprocessor interpret do("a") as doA() and do("b") as doB() and maybe some other doUndefined() if unknown x provided? To clarify: I want to map x parameter to arbitrary code or function call, not just call do{uppercase_x}(). It must be done at compile time. And the x parameter must be a string.

Thanks!

g00dds
  • 195
  • 8
  • If it is compile time, _why_ does `x` has to be a string? Why not `do(a)` instead of `do("a")`? – hyde Aug 24 '22 at 04:51
  • @hyde, it would be great if it would be possible with C string. Is it possible with parameter without quotes? The parameter may also contain spaces, like other strings. Would it be possible with `do(Hello world)`? – g00dds Aug 24 '22 at 04:55
  • 5
    There's an [XY Problem](http://mywiki.wooledge.org/XyProblem) lurking in the undergrowth. What you're seeking to do is close to abuse of macros. It won't make your code any easier to read, nor will it make it easier to understand. Why do you think writing `do("a")` is clearer than just writing `doA()`? – Jonathan Leffler Aug 24 '22 at 04:58
  • 1
    This doesn't help them with the catch-all `doUndefined` for bad arguments. This really seems like the kind of problem that requires some dynamic dispatch, rather than a tangle of sketchy macros. I agree with the XY problem sentiment. The question should be updated to ask about the exact problem that requires solving, and _not_ about the code OP thinks will solve it. – paddy Aug 24 '22 at 05:03
  • 1
    Depending on what you mean by "compile time", a good compiler is likely to optimize `x[0] == 'a' ? doA() : doB()` into just `doA()` or `doB()` if `x` is a string literal or similar. – Nate Eldredge Aug 24 '22 at 05:03

1 Answers1

5

It can't be done for arguments with spaces. Without spaces, you can define macros for each allowed value. Those macros, in turn, can expand to your desired macros, insulating the argument names from the final macro names. For example:

#define do(x) do_##x

#define do_a doA
#define do_b doB

Then do(a) would expand to doA and do(b) would expand to doB.

Update: As paddy mentioned, do is a reserved keyword in C, so you should pick a different name for your macro.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41