There were right significant answers, but I would like to make some clarifications. Unfortunately, a test example was formed incorrectly. We can write this way:
void F1()
{
size_t i = 0;
std::wstring s;
s = (i < 0) ? L"ABC" : L"DEF";
s = (i != -1) ? L"ABC" : L"DEF";
}
In such case the analyzer will issue two V547 warnings:
- V547 Expression 'i < 0' is always false. Unsigned type value is never
< 0. consoleapplication1.cpp 15
- V547 Expression 'i != - 1' is always
true. consoleapplication1.cpp 16
(V519 will also take place, but it does not relate to the issue.)
So, the first V547 warning is print because the unsigned variable cannot be less than zero. It also doesn’t matter what value the variable has.
The second warning is issued because the analyzer reacts that 0 is assigned to the variable i and this variable does not change anywhere.
Now let's write another test example so that the analyzer knew nothing about the value of the variable i
:
void F2(size_t i)
{
std::wstring s;
s = (i < 0) ? L"ABC" : L"DEF";
s = (i != -1) ? L"ABC" : L"DEF";
}
Now there will be only one V547 warning:
- V547 Expression 'i < 0' is always false. Unsigned type value is never < 0. consoleapplication1.cpp 22
The analyzer can say nothing about the (i != -1)
condition. It is perfectly normal and it can be, for example, the comparison with npos
, as have already noticed.
I wrote this in case if someone decides to test a source example using PVS-Studio, taking it out of the question. This person will be surprised, when he sees two warnings, though it is discussed that there will be only one.
i != -1
in isolation – Pepi != -1
is not always true! – Witi != -1
as “comparing signed and unsigned”. Such warning is harmful, because somebody might silence it by changing it toi != unsigned(-1)
ori != -1u
, but that would break the code (i
issize_t
and that might be larger thanunsigned
).i != -1
is the most reasonable way in most cases. – Witi<0
but static analysis of this code shows thati
is always 0 when this check occurs, thereforei != -1
is redundant at this point in the code. PVS-Studio simply chooses to only warn about the former not the latter. – Raguelragweedi < 0
is never true wheni
is asize_t
,i <= -1
will always be true wheni
is asize_t
. – Roundfaced