Converting C/C++ Code to D (#define extern)

Brad Roberts braddr at puremagic.com
Mon Oct 2 22:37:11 PDT 2006


Bill Baxter wrote:
> Serg Kovrov wrote:
>> Hi exiquio, you wrote:
> 
>>>
>>> #define MovePiece(pos,from,to) do {                 \
>>>     PieceList(pos,to) = PieceList(pos,from);            \
>>>     PrevPiece(pos,NextPiece(pos,to)) = to;      \
>>>     NextPiece(pos,PrevPiece(pos,to)) = to;      \
>>>   } while(0)
>>
> 
>> Although later is somewhat suspicious - how loop meant to break?. 
>> Perhaps there is another macro called as function, that has a break 
>> statement. You could investigate what exactly it should do and rewrite 
>> it more clear.
>>
> 
> That's a C preprocessor trick so that a call to the macro can pretend to 
> be a regular function call.  It allows you to introduce a local 
> variable, or have an if-else or loop in the macro.  E.g.
> 
> #define MaybeDoIt(cond) if (cond) \
>    { int ret; \
>      ret = prepareToDoIt(); \
>      doIt(); \
>    }
> 
> If you write it like that you can't call it like "MaybeDoIt(false);". 
> The ';' on the end is syntactically incorrect.  Many C/C++ compilers 
> would barf on it.  So you wrap it in a do while which needs a ';' at the 
> end:
> #define MaybeDoIt(cond) do{\
>    if (cond) \
>    { int ret; \
>      ret = prepareToDoIt(); \
>      doIt(); \
>    } \
>    while(0)
> 
> In this case it's really not necessary, though.  No loops, if-elses, or 
> local variables are introduced so it could just be:
> 
>  #define MovePiece(pos,from,to)                \
>      PieceList(pos,to) = PieceList(pos,from);  \
>      PrevPiece(pos,NextPiece(pos,to)) = to;    \
>      NextPiece(pos,PrevPiece(pos,to)) = to
> 
> Then you would call it like "MovePiece(a,b,c);" from your code.
> 
> Either way this should just be made into a regular function.  (Which D 
> will inline if it feels like it).
> 
> --bb

But you can't do:

if (cond)
     MovePiece(a, b, c);

and have it behave as you'd expect with your suggested definition but it 
would work as expected in the original form.  do/while loops form a 
valid block, and that's the key difference.

Later,
Brad



More information about the Digitalmars-d-learn mailing list