0

I have demostrative code below. I would expect the result will be initialized array.

#define _NAME name
#define CFIT(name)\
    { _NAME },

const char * idns[] = {
    CFIT("address")
    CFIT("device_id")
    CFIT("device_bh")
    CFIT("device_hw")
    CFIT("device_fw")
    "" };

...but preprocesor create this:

const char * idns[] = {

    { name },
    { name },
    { name },
    { name },
    { name },
    ""
};

Surprisingly the C++ preprocesor works as expected. Replace _NAME macro with 'name' token direcly works as well. Any hints? Using 32b mingw 5.3.0.

bernau84
  • 15
  • 2
  • That has more to do with the notorious brokenness of Microsoft's preprocessor than with C-vs-C++ differences. `name` is the right expansion. If it happens to be the name of the current macro's argument, it shouldn't expand further. – Petr Skocik Dec 07 '18 at 15:41
  • The seems it works with C++ was my mistage (again). Thank you. – bernau84 Dec 10 '18 at 08:17

1 Answers1

0

Let's look at only one invocation; I'll pick this one:

CFIT("address")

The preprocessor first performs argument substitution. At this phase, if the parameter (name) is in the replacement list ({ _NAME },; I'm just stripping whitespace here), and not being stringified or participating in a paste, then the argument is fully expanded and the results are replaced with the parameter. Here, name does not appear in that replacement list, so there's nothing to do. So after argument substitution, you have { _NAME },.

The next step is rescan and further replacement (after stringification and pastes occur, of which there's none). At this stage, the remaining tokens are rescanned so that macros can expand (after blue painting the current macro, but that has no effect here). During this stage, _NAME is recognized as an object-like macro, so its expansion commences. That happens to expand to name, but we're already done with argument substitution so it has no relation to the parameter name at this point... it's just another token.

H Walters
  • 2,634
  • 1
  • 11
  • 13
  • Thanks. Clear now. – bernau84 Dec 10 '18 at 08:18
  • The truth is that I need solved something more complex (like variable macro arguments) but I prepare not to descriptive example. Luckily I've found answer [elsewhere](https://stackoverflow.com/questions/3046889/optional-parameters-with-c-macros?noredirect=1&lq=1) on stackoverflow. So may this link can help others who can not even express what they are looking for, like me:) – bernau84 Dec 10 '18 at 08:32