警告 C26454:算术溢出:“-”运算在编译时产生负的无符号结果 (io.5)

Warning C26454: Arithmetic overflow: '-' operation produces a negative unsigned result at compile time (io.5)

代码分析:

ON_NOTIFY(TCN_SELCHANGE, IDC_TAB_HISTORY_TYPE,
  &CAssignHistoryDlg::OnTcnSelchangeTabHistoryType)

警告 C26454:

Arithmetic overflow: '-' operation produces a negative unsigned result at compile time (io.5).

TCN_SELCHANGE的定义是:

#define TCN_FIRST (0U-550U)
#define TCN_SELCHANGE           (TCN_FIRST - 1)

我看不出我还能做什么!

您正试图从一个较小的无符号值中减去一个较大的无符号值,这导致结果绕过零。在您的情况下,我假设 TCN_FIRST 定义为 0,因此将 TCN_SELCHANGE 设置为 1 将解决问题。

您还应该使用 constexprconst 而不是定义。

根据 MSDN:

Arithmetic overflow checks in C++ Core Check

C26451 RESULT_OF_ARITHMETIC_OPERATION_CAST_TO_LARGER_SIZE :[operator] operation wraps past 0 and produces a large unsigned number at compile time. This warning indicates that the subtraction operation produces a negative result which was evaluated in an unsigned context. This causes the result to wrap past 0 and produce a really large unsigned number, which can result in unintended overflows.

1 // Example source:
2 unsigned int negativeunsigned() {
3    const unsigned int x = 1u - 2u; // C26454 reported here
4    return x;
5 }

1 // Corrected source:
2 unsigned int negativeunsigned() {
3     const unsigned int x = 4294967295; // OK
4     return x;
5 }

In the corrected source, a positive value was assigned to the unsigned result.

//windows header file:
#define TCN_FIRST (0U-550U)
#define TCN_SELCHANGE           (TCN_FIRST - 1)

//user file:
...
unsigned int i = TCN_SELCHANGE;

以上代码在C++中有效,编译时应该没有任何警告。没有溢出,就是-550U写成#define TCN_FIRST 0xFFFFFDDA或者0xFFFFFFFFU-549U

就更清楚了

代码分析似乎使用了不同的方法并发现溢出。

可能的解决方案:

禁用代码中的警告:

#pragma warning( push )
#pragma warning( disable : 26454 )

BEGIN_MESSAGE_MAP(CMyDialog, CDialogEx)
    ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, OnTcnSelchangeTabHistoryType)
END_MESSAGE_MAP()

#pragma warning( pop )

或者,禁用代码分析规则中的警告
Use the code analysis rule set editor