For the following snippet:
size_t i = 0;
std::wstring s;
s = (i < 0) ? L"ABC" : L"DEF";
s = (i != -1) ? L"ABC" : L"DEF";
PVS-Studio analysis logs warning for the first condition i < 0
, as expected:
V547 Expression 'i < 0' is always false. Unsigned type value is never < 0. test_cpp_vs2017.cpp 19
Why PVS does not issue any warning about the second, also suspicious condition i != -1
reporting it as always true, for instance?
Because that'd be a useless, invalid warning.
size_t
is an unsigned type, and due to the way integer conversions work (see [conv.integral]/2),-1
converted (implicitly here) tosize_t
is equal toSIZE_MAX
.Consider the fact that this is the actual definition of
std::string::npos
in libstdc++:If PVS-Studio warned about
i != -1
, would it also need to warn abouti != std::string::npos
?On the other hand, an unsigned value can never be smaller than 0, due to it being unsigned, so
i < 0
is likely not what the programmer wanted, and thus the warning is warranted.