Programming Utilities Guide

Arithmetic Built-Ins

m4 provides three built-in macros for doing integer arithmetic. incr() increments its numeric argument by 1. decr() decrements by 1. So, to handle the common programming situation in which a variable is to be defined as "one more than N," you would use:

define(N, 100) 
define(N1, `incr(N)')

That is, N1 is defined as one more than the current value of N.

The more general mechanism for arithmetic is a built-in macro called eval(), which is capable of arbitrary arithmetic on integers. Its operators, in decreasing order of precedence, are

+ - (unary) 
(**(** 
(** / % 
+ - 
== != < <= > >= 
! ~ 
& 
| ^ 
&& 
|| 

Parentheses may be used to group operations where needed. All the operands of an expression given to eval() must ultimately be numeric. The numeric value of a true relation (like 1 > 0) is 1, and false is 0. The precision in eval() is 32 bits.

As a simple example, you can define M to be 2(**(**N+1 with

define(M, `eval(2(**(**N+1)')

Then the sequence

define(N, 3) 
M(2)

gives 9 as the result.