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

代码分析:

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

警告 C26454:

<块引用>

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

TCN_SELCHANGE的定义是:

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

我看不出我还能做什么!

解决方案

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

你也应该使用 constexprconst 而不是定义.

根据 MSDN:

C++ 核心检查中的算术溢出检查

<块引用>

C26451 RESULT_OF_ARITHMETIC_OPERATION_CAST_TO_LARGER_SIZE:[operator] 操作结束0 并在编译时产生一个大的无符号数.此警告表明减法运算产生了在无符号上下文中评估的否定结果.这会导致结果超过 0 并产生一个非常大的无符号数,这可能导致意外溢出.

1//示例源:2无符号整数负无符号(){3 常量无符号整数 x = 1u - 2u;//这里报告了 C264544 返回 x;5 }1//更正的来源:2无符号整数负无符号(){3 常量无符号整数 x = 4294967295;//行4 返回 x;5 }

<块引用>

在更正后的源中,为无符号结果分配了一个正值.

Code analysis:

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

Warning C26454:

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

The definition of TCN_SELCHANGE is:

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

I can't see what else I can do!

解决方案

You are trying to subtract a larger unsigned value from a smaller unsigned value and it's causing the result to wrap past zero. In your case, I assume TCN_FIRST is defined as 0 so setting TCN_SELCHANGE to one will fix the problem.

You should also be using constexpr or const instead of defines anyway.

According to 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.

相关文章