0

I am trying to write something like this:

#define set(x){cout<< x}
int main() {
    set(#ifdef A  1 #else 3 #endif );
    return 0;
}

But it does not work, my question is why? Why doesn't C allow the code to work? what the problem with ifndef inside a macro?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Moshe Levy
  • 174
  • 9
  • 2
    Because the syntax isn't specified that way, simple as that. Why _should_ C allow this strange code to work and what problem would that solve? – Lundin Oct 16 '20 at 11:31
  • If I want to send the function a parameter depends on the define? And It does not seem hard to implement it, so why not? – Moshe Levy Oct 16 '20 at 11:33
  • 1
    Why can't you use `#ifdef A #define B 1 #else #define B 3 #endif` ... `set(B);`? – Lundin Oct 16 '20 at 11:36
  • What does "not allowed" mean? Do you get an error message? – nicomp Oct 16 '20 at 11:40
  • @Lundin I can, just interests why this code does not work, thought that maybe there is some reason(hard to implement, something that refers to the preprocessor, etc), but as you say, maybe it just a matter of syntax – Moshe Levy Oct 16 '20 at 11:40
  • @nicomp Compile error : stray '#' in program set(#ifdef A 1 #else 3 #endif ); – Moshe Levy Oct 16 '20 at 11:41
  • 1
    your code is not valid C. And it doesn't compile in C++ either. See also [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/995714) – phuclv Oct 16 '20 at 12:14

1 Answers1

3

Who said no?

set(
    #ifdef A
        1 
    #else
        3
    #endif
);

The above snippet works as expected. Demo on Godbolt

# is a special character that starts a preprocessor directive and must be at the start of the line (after optional whitespaces) so you must separate into new lines. Anyway that's not what people usually do, because they'll do like this

#ifdef A
    set(1);
#else
    set(3);
#endif

or

#ifdef A
    #define VAL 1
#else
    #define VAL 3
#endif
set(VAL);

Note that cout << is not C and you're missing a semicolon in the macro. It should be {cout<< x;}

phuclv
  • 37,963
  • 15
  • 156
  • 475