# Boost.Preprocessor - Reference

###

# Boost.Preprocessor

## Reference

Prev Next Macros Headers

# #include <boost/preprocessor/for.hpp>

## #define BOOST_PP_FOR(STATE,PRED,OP,MACRO)

Repeats `MACRO(R,STATE)` and iterates `OP(R,STATE)` while `PRED(R,STATE)` is true.

In other words, expands to the sequence:

      MACRO(R,STATE)
      MACRO(R,OP(R,STATE))
      MACRO(R,OP(R,OP(R,STATE)))
      ...
      MACRO(R,OP(R,OP(...OP(R,STATE)...)))

The length of the sequence is determined by `PRED(R,STATE)`.

For example,

      #define PRED(R,STATE) BOOST_PP_LESS(BOOST_PP_TUPLE_ELEM(2,0,STATE),BOOST_PP_TUPLE_ELEM(2,1,STATE))
      #define OP(R,STATE) (BOOST_PP_INC(BOOST_PP_TUPLE_ELEM(2,0,STATE)),BOOST_PP_TUPLE_ELEM(2,1,STATE))
      #define MACRO(R,STATE) BOOST_PP_TUPLE_ELEM(2,0,STATE)
      BOOST_PP_FOR((0,3),PRED,OP,MACRO)

expands to:

      0 1 2

### Legend

- STATE is the current state of iteration. The state is usually a tuple.
- PRED is the condition for iteration. It must expand to a decimal integer literal.
- OP is the iterated macro. Note that if the state is a tuple, then OP(R,STATE) usually expands to a tuple of the same number of elements.
- MACRO is the state instantiation macro.
- R is the recursion depth and should only be used as a parameter to other macros using BOOST_PP_FOR() or for invoking BOOST_PP_FOR##R() directly. For each macro using BOOST_PP_FOR(), e.g. BOOST_PP_LIST_FOR_EACH(), there is a version of the macro, e.g. BOOST_PP_LIST_FOR_EACH_R(), distinguished by the R suffix, that accepts an additional recursion depth as the first parameter. This technique is necessary to avoid recursively expanding the same macro again, which is not permitted by the C++ preprocessor.

### BOOST_PP_REPEAT() vs BOOST_PP_FOR()

BOOST_PP_FOR() is a generalization of BOOST_PP_REPEAT(). This means that BOOST_PP_REPEAT() can be implemented using BOOST_PP_FOR(). However, BOOST_PP_REPEAT() was introduced earlier, is generally easier to use, and is still quite useful on its own.

### 2D and 3D repetition

BOOST_PP_FOR() can be used for multidimensional repetition simply by invoking BOOST_PP_FOR##R() directly.

### Test

- for_test.cpp

Prev Next Macros Headers

Revised

© Copyright Housemarque Oy 2002

Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.