Re: Evaluating arithmetic expressions with macros (eval)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi,

On 2023-10-04, Sébastien Hinderer <Sebastien.Hinderer@xxxxxxxx> 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





[Index of Archives]     [GCC Help]     [Kernel Discussion]     [RPM Discussion]     [Red Hat Development]     [Yosemite News]     [Linux USB]     [Samba]

  Powered by Linux