I
C++ / C#

Is it possible to make an expression like #define name #if fds == fds *dosomething* #else *dosomething* #endif valid in C? And if so, how?

for practice, I made my own interpreter of the Yap I lured. I did not do it as expected, but simply connected all the stages in one cycle, but this is not the point. When I started to make a command system (I wanted to start with just print built into the interpreter, and not as a separate function), I decided to make a state system from macros. And there it took a similar following construction:

#define somemacro(arg) #if arg == sd\
        printf ("some text 1");\
        #else\
        printf ("some text 2");\
        #endif

But compile, because #if #else #endif construction cannot be written in one line. Is there any way to make this construct valid or make an equivalent that works the same way?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AnT, 2020-10-04
@TheCalligrapher

To do just that: no, it's impossible. Preprocessor macro definitions cannot contain preprocessor directives.
Make an "equivalent that works the same way" (sic): no one knows the answer to this question because you didn't bother to clearly explain what you're trying to do with this cryptic set of tokens. The key here is the nature of the condition arg == sd. Is it a compile time value?
In any case, it is not clear why you were not satisfied with the usual

#define somemacro(arg) if ((arg) == (sd))\
  printf ("some text 1");\
else\
  printf ("some text 2");

S
Sergey, 2020-10-04
@Gryphon88

Something similar can be done through P99, M4 or Boost.Preprocessor, but you don’t need to do this: this is very black magic (in fact, declarative programming in Refal-machine terms), and after a couple of weeks you will forget how it works at all. If you really need to do code generation, use the appropriate tools, as a last resort, insert a Perl or Python script in pre-build that will parse and complete the existing C code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question