[fpc-pascal] Hack for C-like macro functions — will it work in future?

Constantine Yannakopoulos alfasud.ti at gmail.com
Wed Sep 24 11:37:00 CEST 2014


On Wed, Sep 24, 2014 at 12:17 PM, Sven Barth <pascaldragon at googlemail.com>
wrote:

> Am 24.09.2014 10:15 schrieb "Tomas Hajny" <XHajT03 at hajny.biz>:
> > However, the trunk compiler offers also another option, although it may
> or
> > may not be usable for you. In particular, take the following:
> >
> > ---------
> > var
> >  S2: string;
> >
> > procedure Log (S: string);
> > begin
> >  {$IFDEF TEST}
> >   WriteLn (S);
> >  {$ENDIF TEST}
> > end;
> >
> > begin
> >  ReadLn (S2);
> >  Log ('Input = ' + S2);
> > end.
> > =========
> >
> > If this is compiled with trunk compiler using -OoREMOVEEMPTYPROCS
> (without
> > -dTEST), procedure Log is not called at all and the concatenation of
> > strings in its parameter is skipped as well.
>
> Another possibility would be to define Log() as "inline", which should get
> rid of the call and maybe the concatenation as well and already works in
> 2.6.x (though "array of const" would not be supported if needed)
>
Another technique​ I have used in Delphi and works in fpc as well is using
the Assert() procedure with a function that has side-effects as argument.
E.g.:

function Log(const S: string): Boolean; inline;
begin
  WriteLn(S);
  Result := True;
end;

begin
  Assert(Log('Hello'),  '');
​end;​

​When the program is compiled with assertions enabled it will output a
"Hello". ​​When it is compiled with assertions disabled the call to DoWrite
and possibly DoWrite itself will be omitted from the exe by the compiler.
No IFDEFs and no macros necessary.

--Constantine
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20140924/56fd0c31/attachment.html>


More information about the fpc-pascal mailing list