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';
}
}
CodePudding user response:
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.
CodePudding user response:
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.
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.)
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 asconstexpr auto sizeNotSet = static_cast<unsigned>(-1);
.Express your magic value as an unsigned value.
sizeB != std::numeric_limits<unsigned>::max()
orsizeB != (0u - 1)
.
CodePudding user response:
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.