I am trying to understand the reasoning behind this particular suggestion in Visual Studio 2022, as it doesn't seem to make sense to me. Here's the simple code:
static constexpr uint32_t MAX_ELEMENTS = 100000;
const std::vector<int> A{ some random ints };
std::vector<bool> found(MAX_ELEMENTS);
for (int value : A)
{
if (value > 0 && value <= MAX_ELEMENTS)
found[value - 1] = true; // Problem it complains about is the value - 1.
}
It suggests that a "sub-expression may overflow before being added to a wider type". Now obviously the condition-if prevents this from ever happening, but what's the reasoning here?
Now if this was a Spectre thing, I could understand that the compiler would add a memory fence to stop any speculative execution of the statement after the if, but I don't think that's the answer here.
My only thinking is that it has to do with the subscript operator on the vector; that its index is of a type larger than int and is implicitly cast to size_t?
Just seems a little unintuitive that the below is an issue:
found[value - 1]
and its perfectly fine to do this,
int a = value - 1;
found[a];
when the end result is the same. What am I missing here in terms of understanding?