Search code examples
pvs-studio

RangeAnalysis and V3022


Consider the code below:

for (var i = int.MaxValue - 2; i < int.MaxValue; i++)
{
    Console.WriteLine(i);
}
Console.WriteLine();

for (var i = int.MaxValue - 2; i <= int.MaxValue - 1; i++)
{
    Console.WriteLine(i);
}
Console.WriteLine();

for (var i = int.MaxValue - 2; i <= int.MaxValue; i++)
{
    Console.WriteLine(i);
}

The two first loops are expected to print out only the third and second largest integer. The last loop has a bug where i will overflow to int.MinValue and causing an infinite loop.

Running it gives the expected output.

2147483645
2147483646

2147483645
2147483646

2147483645
2147483646
...

PVS Studio raises three warnings:

V3022 Expression 'i < int.MaxValue' is always true.

V3022 Expression 'i <= int.MaxValue - 1' is always true.

V3022 Expression 'i <= int.MaxValue' is always true.

The bug in the last loop is correctly reported, but the two first warnings are false positives.


Solution

  • We have fixed this false positive. The fix will be available with the next release.