Andrew Truckle
Andrew Truckle

Reputation: 19097

Warning C26451 Arithmetic overflow: Using operator '-'

I don't understand why this issue is being flagged:

InitAssignmentCell(iNumRows - 1, strDescription, IMG_UNCHECKED, static_cast<LPARAM>(iNumRows - 1));

The definition for that method is:

InitAssignmentCell(int iRow, CString strAssignment, int iCheckState, LPARAM lParam)

So the final parameter is a LPARAM. Yet I am seeing some squiggles:

enter image description here

Warning C26451 Arithmetic overflow: Using operator '-' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator '-' to avoid overflow (io.2).

I don't understand this because iNumRows is of type int.

I have seen the answer here which is along similar lines and my gut is that this is a false warning.

Upvotes: 1

Views: 1234

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51825

The C26451 warning from the MSVC static analyser is very pedantic. It warns against the possibility that you may be assuming that promotion is automatically performed before the cast (which it is not).

To silence the warning, do the cast before the arithmetic. So, instead of:

InitAssignmentCell(iNumRows - 1, strDescription, IMG_UNCHECKED, static_cast<LPARAM>(iNumRows - 1));

Use:

InitAssignmentCell(iNumRows - 1, strDescription, IMG_UNCHECKED, static_cast<LPARAM>(iNumRows) - 1L);

You don't really need the L (or LL for 64-bit builds) suffix, but it makes it clear to future readers that you know what you're doing. A more precise (but ugly) specification of the constant would be static_cast<LPARAM>(1).

Upvotes: 1

Related Questions