The BOOST_PP_WHILE macro represents a looping construct.


BOOST_PP_WHILE(pred, op, state)


A binary predicate of the form pred(d, state).  This predicate is expanded by BOOST_PP_WHILE with the next available iteration d and the current state.  This predicate must expand to value in the range of 0 to BOOST_PP_LIMIT_MAG. The construct continues to loop until this predicate returns 0.  When this predicate returns 0, BOOST_PP_WHILE returns the current state.
A binary operation of the form op(d, state).  This operation is expanded by BOOST_PP_WHILE with the next available iteration d and the current state.  This macro is repeatedly applied to the state, each time producing a new state, until pred returns 0.
The initial state.  Often this argument is a tuple.


This macro iterates op(d, state) while pred(d, state) is non-zero.  In other words expands to:
op(d, ... op(d, op(d, state)) ... ).
The d value that is passed to both pred and op represents the next available iteration.  Other macros that have _D suffix variants internally use BOOST_PP_WHILE--for example, BOOST_PP_ADD and BOOST_PP_ADD_D.  Using these _D versions is not strictly necessary, but passing the d value (that passed to pred or op) to these macros allows them to reenter BOOST_PP_WHILE with maximum efficiency.
To directly use this d value, rather than simply passing it to another macro, see BOOST_PP_WHILE_d.
Previously, this macro could not be used recursively inside BOOST_PP_WHILE.  This limitation no longer exists, as the library can automatically detect the next available iteration.

See Also


Header:  <boost/preprocessor/control/while.hpp>

Sample Code

#include <boost/preprocessor/arithmetic/add.hpp>
#include <boost/preprocessor/control/while.hpp>
#include <boost/preprocessor/tuple/elem.hpp>

#define PRED(n, state) BOOST_PP_TUPLE_ELEM(2, 1, state)

#define OP(d, state) \
   OP_D( \
      d, \
      BOOST_PP_TUPLE_ELEM(2, 0, state), \
      BOOST_PP_TUPLE_ELEM(2, 1, state) \
   ) \

#define OP_D(d, res, c) \
   ( \
      BOOST_PP_ADD_D( \
         d, \
         res, \
         BOOST_PP_DEC(c) \
      ), \
      BOOST_PP_DEC(c) \
   ) \

#define SUMMATION(n) \
      2, 0, \
      BOOST_PP_WHILE(PRED, OP, (n, n)) \
   ) \

SUMMATION(3) // expands to 6
SUMMATION(4) // expands to 10

Copyright Housemarque Oy 2002
Copyright Paul Mensonides 2002

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at