Converting C/C++ Code to D (#define extern)
Bill Baxter
dnewsgroup at billbaxter.com
Mon Oct 2 22:06:46 PDT 2006
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
More information about the Digitalmars-d-learn
mailing list