Re: Evaluating arithmetic expressions with macros (eval)

Nick Bowler <[email protected]>
Newsgroups gmane.comp.sysutils.autoconf.general
Message-ID <CADyTPEy6d=3a+DW_YXxFy333GujNOuN_Zxo7doSZUQn+GqNLMQ@mail.gmail.com>
Hi,

On 2023-10-04, Sébastien Hinderer <[email protected]> wrote:
> I find myself stuck with something which I assume is trivial. I define:
>
> m4_define([X], [9])
> m4_define([Y], [3])
>
> And I would like to define Z as being the arithmetic sum of X and Y and
> can seem to get it.
>
> I tried several variations of eval but had no success. I understand
> that all the macros need to be expanded before eval is called but I
> don't understand how to do it.

The short answer for your specific example is to simply not quote the
arguments:

    m4_define([Z], m4_eval(X + Y))

This approach is probably sufficient for most typical uses of m4_eval,
as there would seem to be little chance of unwanted macro expansion.

Some details, when m4 sees the following macro expansion:

m4_define([Z], m4_eval(X + Y))

- The first argument contains no unquoted text, so no macro expansion is
  performed.  The quotes are removed, and the first argument is "Z".

- The second argument contains unquoted text and a macro:

   m4_eval(X + Y).

   - The first argument of this contains unquoted text with two macros,
     X and Y.  These are replaced with 9 and 3, respectively.  There
     are no further macros to expand and no quotes to remove, so the
     actual argument to m4_eval is 9 + 3.

   Now m4_eval(9 + 3) is expanded, giving 12.  There are no further
   macros to expand and no quotes to remove, so the second argument
   to m4_define is 12.

Now m4_define(Z, 12) is expanded.

Hope that helps,
  Nick
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.