Unexpected behaviour using unsigned char in comparison

Falk S. falk-o-mat@gmx.de
Sun Jan 9 18:00:00 GMT 2011


Hi,

in the following program the return value of the test2uc() function is 
always false, however I would expect it to be true.
#include <iostream>
using namespace std;

bool test2uc() {
        typedef unsigned char uchar;
        uchar mask = ~(uchar(0)) << 1;
        return (mask | uchar(true)) == (~ uchar(0));
}

int main(int argc, char** args) {
        cout << test2uc() << endl;
        return 0;
}

Compiled with -ansi -Wall -g -gdwarf-2 -pedantic
g++ (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
g++.exe (GCC) 4.5.0 (MingW)
on Windows 7

I get a "warning: comparison is always false due to limited range of 
data type" when compiling with g++ a c++ file, which I do not understand.
If I change the type of uchar to char, i.e. signed char, I get the 
expected result.

Any ideas?
bye,
Falk



More information about the Gcc-help mailing list