#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
bool compare( const string::size_type i, const string::size_type j )
{
cout << "comparing " << i << " and " << j << "." << endl;
return i < j;
}
void reverse_inplace( std::string &s )
{
std::string::size_type i = 0;
std::string::size_type j = s.size()-1;
cout << "called" << endl;
while( compare(i,j) );
{
cout << i << " " << j << endl;
std::swap(s[i], s[j]);
++i;
--j;
cout << i << " " << j << endl;
}
}
int main()
{
string s( "a" );
reverse_inplace(s);
cout << s << endl;
}
What’s wrong with my code? Why will it keep comparing, return true? and not execute the loop body there’s no ? I tried GCC 4.6 and MSVC 10 SP1. The cout statements in the loop are not being executed for some strange reason.
The loop body isn’t being executed because you have a semicolon after the while() line, which is causing the loop body to be ignored. Therefore, the increment and decrement statements aren’t being hit; neither are the
couts.