fthomas/slhaea

Unary sign operator applied to unsigned type

Closed this issue · 0 comments

MSVC gives a compiler warning for line 841 in slhaea.h, hinting to a possible bug.
The line for which the warning is given is in Block& read(std::istream& is):

is.seekg(-line_str.length()-1, std::ios_base::cur);

The warning from MSVC is:

warning C4146: unary minus operator applied to unsigned type, result still unsigned

If I understand correctly, the issue is the following: line_str.length() returns an unsigned value. Applying the unary minus operator to that value returns another unsigned value, which may be huge.

Example:

unsigned u = 1;
std::cout << -u; // prints 4294967295

I believe this is not the desired behavior.

A possible fix would be to perform a static_cast<std::ptrdiff_t>:

unsigned u = 1;
std::cout << -static_cast<std::ptrdiff_t>(u); // prints -1