[OT] #define

Dukc via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 22 06:52:35 PDT 2017


On Monday, 22 May 2017 at 13:11:15 UTC, Andrew Edwards wrote:
> Sorry if this is a stupid question but it eludes me. In the 
> following, what is THING? What is SOME_THING?
>
>     #ifndef THING
>     #define THING
>     #endif
>
>     #ifndef SOME_THING
>     #define SOME_THING THING *
>     #endif
>
> Is this equivalent to:
>
>     alias thing = void;
>     alias someThing = thing*;
>
> Thanks,
> Andrew

I assume you know that the above part is c/c++ preprocessor, 
which is not normally used at d?

THING is nothing there. If you use it at code, I'm not sure how 
it behaves. Either it does not compile at all, or it behaves as 
nothing (think whitespace). If it's the latter, SOME_THING would 
be a lone asterix. Can be used as operator both unarily and 
binarily. #IFNDEF regonizes all preprocessor declarations, empty 
or not.

The closest D equivalent to #DEFINE is a string mixin. The 
equivalent to above is:
static if (!is(typeof(thing))) enum thing = "";
static if (!is(typeof(someThing))) enum someThing = thing ~ " *";

This is used differently than a preprocessor though. Instead of:

@safe void main()
{   import std.stdio;
     writeln(5 SOMETHING 6);
}

...you have to explicitly mix the text in:

@safe void main()
{   import std.stdio;
     mixin("writeln(5 " ~ someThing ~ " 6);"); //30
}

Because just mixing in text straight away is generally quite an 
ugly solution, so is the syntax. In most cases you would want to 
replace it with a more context-specific solution:

-If the symbol is a literal, an enum literal OF THE TYPE OF THE 
LITERAL is preferred.

-If the symbol is an empty declaration used only for #IFNDEFS, 
version statements are a cood canditate for replacing it. Perhaps 
that's what you're looking for?

-If the symbol is a type, or a name of another global symbol, 
alias is the way to go.

-In the case of function-type #DEFINES, eponymous templates or 
aliases to lambdas are your best bets.

Note, there is no equivalent to #UNDEF in D. But unlike the 
preprocessor, all D symbols cease to exist when their scope ends, 
and in almost all cases that's a much better thing!


More information about the Digitalmars-d-learn mailing list