title: Syntax Error in Preprocessor Macro Code
body: <p>I am trying to write some code for a macro which returns the length of a string, and am attempting to implement it using BOOST_PP_WHILE. The code stems from the fact that a character at a position specified by <code>position</code> of the string represented by a macro argument <code>foo</code> may be obtained by <code>#foo[position]</code>. Compiling using either MSVC or Intel C++ results in similar syntax errors; if you could point out why the code is generating these syntax errors and how I would rectify code, it would be greatly appreciated. <strong>I know that the errors are caused by the code within the <code>PREDICATE</code> macro, but any expression I attempt to use within it barring <code>BOOST_PP_TUPLE_ELEM</code> results in a compile-time error.</strong></p>
  
  <p><strong>Errors:</strong></p>
  
  <pre><code>prog.cpp:47:1: error: pasting "BOOST_PP_BOOL_" and ""\"Hello, World!\""" does not give a valid preprocessing token
  prog.cpp: In function ‘int main(int, char**)’:
  prog.cpp:47: error: ‘BOOST_PP_TUPLE_ELEM_2_1’ was not declared in this scope
  </code></pre>
  
  <p>As one would expect, the line numbers are not very useful since both point to the line at which the macro <code>MACRO_STRLEN</code> is called.</p>
  
  <p><strong>Code</strong></p>
  
  <p>Below follows the source listing in which I attempt to implement the macro which I describe.</p>
  
  <pre><code>#include &lt;boost/preprocessor/arithmetic/dec.hpp&gt;
  #include &lt;boost/preprocessor/arithmetic/inc.hpp&gt;
  #include &lt;boost/preprocessor/comparison/equal.hpp&gt;
  #include &lt;boost/preprocessor/control/while.hpp&gt;
  #include &lt;boost/preprocessor/tuple/elem.hpp&gt;
  #include &lt;cstdio&gt;
  
  #define TEST_STRING0 "Hello, World!"
  
  #define MACRO_IS_NULL_IMPL(x, position) \
      #x[position] == '\0'
  
  #define MACRO_IS_NULL(x, position) \
      MACRO_IS_NULL_IMPL(x, position)
  
  #define PREDICATE_D(string, position) \
      MACRO_IS_NULL(string, position)
  
  #define PREDICATE(n, state) \
      PREDICATE_D( \
          BOOST_PP_TUPLE_ELEM(2, 0, state), \
          BOOST_PP_TUPLE_ELEM(2, 1, state) \
      )
  
  #define OPERATION_D(string, position) \
      ( \
          string, \
          BOOST_PP_INC(position) \
      )
  
  #define OPERATION(d, state) \
      OPERATION_D( \
          BOOST_PP_TUPLE_ELEM(2, 0, state), \
          BOOST_PP_TUPLE_ELEM(2, 1, state) \
      )
  
  #define MACRO_STRLEN_IMPL(string) \
      BOOST_PP_TUPLE_ELEM( \
          2, 1, BOOST_PP_WHILE(PREDICATE, OPERATION, (string, 0)) \
      )
  
  #define MACRO_STRLEN(string) \
      MACRO_STRLEN_IMPL(string)
  
  int main(int argc, char ** argv) {
  
      printf("String length: %d.\n", MACRO_STRLEN(TEST_STRING0));
      return 0;
  
  }
  </code></pre>