#14 Print inconsistency - c++ operator precedance



In the file rapidxml_print.hpp, the out stream iterator is used in 2 ways:
*out++ = smth
*out = smth; ++out;

Because the precedance of operator++ is higher than operator*, in *out++ the iterator will be incremented before changing the value, as opposite to "*out = smth; ++out;". This can lead to cases where the stream iterator is incremented 2 times, thus the output is incorrect:

Output :
<?xml versio=" 1." encodin=" utf-"?>
< Configuratio versio=" 0.9."/>

Expected output :
<?xml version="1.0" encoding="utf-8"?>
<Configuration version="0.9.5"/>

The solution is easy: all incrementations should be done the same way, so changing every "*out++ = smth" to "*out = smth,++out;" solves the problem.
I have done this in the attached file.


  • Darktib

    Darktib - 2011-03-19

    Corrected print utility file

  • mack

    mack - 2011-03-24


    Postfix operator ++ returns value of expression _before_ the increment happens, so it cannot be causing the behaviour you describe. In short, the effect of these two expressions:

    *out++ = 'a'
    *out = 'a'; out++;

    is identical. Do you have a small example where I can reproduce the problem you're having?

    [You can verify the behaviour of operator ++ yourself by running the program attached below. As you will see, the output is 'ba' for both cases.]

    #include <iostream>

    char buffer1[3] = "aa";
    char buffer2[3] = "aa";

    int main()
    char *ptr1 = buffer1;
    char *ptr2 = buffer2;
    *ptr1++ = 'b';
    *ptr2 = 'b'; ptr2++;
    std::cout << buffer1 << std::endl; // will output "ba"
    std::cout << buffer2 << std::endl; // will output "ba"

  • Darktib

    Darktib - 2011-04-01


    Thanks for your response.

    The problem I describe is a real problem I have encountered; when I changed what I described, and only it, it worked perfectly...

    I know that postfix ++ returns the value before the increment, but this problem was real... Maybe the compiler was messed up because of the stream I used - it was not a stl stream...


Log in to post a comment.