[OCLUG-devel] Interesting little g++ bug

Christopher Smith x at xman.org
Tue Sep 6 17:33:48 PDT 2005


Ran in to this funny bug today:

#include <iostream>

using namespace std;

int main()
{
    cout << dec << -1 << endl;
    cout << hex << -1 << endl;
    return 0;
}

So, what's the output? Well, you'd think it'd be:
-1
-1

But instead it's:
-1
ffffff

Why? Because while the facet handling the formatting of integers uses
modular arithmetic and checks to see if it should print out a
positive/negative sign when working with decimal formatting, when doing
octal or hex formatting it uses bitwise arithmetic and doesn't check for
whether it should print any sign. It does this despite the fact that its
template arguments clearly allow it to determine whether it is dealing
with signed or unsigned integers.

Interestingly, while the code for iostreams doesn't actually use the
printf() code, it does mimic the behavior (printf() only handles hex
formatting for unsigned integers).

--Chris


More information about the OCLUG-devel mailing list