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

前端 未结 2 2013
孤独总比滥情好
孤独总比滥情好 2021-02-10 02:24

Code analysis:

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

Warning C26454:

2条回答
  •  执笔经年
    2021-02-10 02:58

    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.

提交回复
热议问题