简体   繁体   中英

How can I fix it "comparison between signed and unsigned integer expressions [-Werror=sign-compare]"

I tried to add unsigned, but the error still occurred, cpplint swears a lot because of this, I'm just tired and want to sleep(

string MinHeap::get_binary_string(unsigned int n,
    unsigned int bit_size = -1) {
    stringstream stream;
    string reverse_binary, binary_str;
    do {
        stream << n % 2;
        n /= 2;
    } while (n);
    unsigned int sizeB = bit_size;
    if (sizeB != -1 && stream.str().size() < sizeB) {
        unsigned int padding_size = sizeB - stream.str().size();
        while (padding_size--) {
            stream << '0';
        }
    }

Do you understand why your unsigned ints shouldn't be defined to -1? That would lead you into undefined code. Either declare them signed or pick a different default value.

The problem is in the expression sizeB != -1 .

The variable sizeB is an unsigned int, and the expression -1 results in a signed int. Since comparing signed values to unsigned values is very often a programming error, many compilers will warn you when it happens.

In your case, the -1 is just a special value carved out of the otherwise expected range of sizes. So it's not actually a bug.

There are many ways to change the code to do the same thing while assuring the compiler that you know what you're doing.

  1. Don't use unsigned types. There are many folks on the C++ standards committee who believe that making sizes unsigned was once a necessary evil but is now a bad programming practice. (I don't find their arguments entirely persuasive, and it's often impractical to switch to signed values without breaking existing code and library interfaces.)

  2. Make the implicit type conversions explicit. One way to do this would be to rewrite the expression as sizeB != static_cast<unsigned>(-1) . As @Phil1970 suggested, you can define a constant with your magic value as the right type, though I would probably write it as constexpr auto sizeNotSet = static_cast<unsigned>(-1); .

  3. Express your magic value as an unsigned value. sizeB:= std::numeric_limits<unsigned>::max() or sizeB != (0u - 1) .

sizeB != -1 --> sizeB != -1u .

Consider the same with other constants 2 --> 2u , etc. Make them unsigned . No cast needed.

Avoid mixing sign-ness in integer math.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM