本文介绍了C ++ while循环优化工作不正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code段:

I have this code segment:

#include <stdio.h>

int main(int argc, const char** argv)
{
    int a = argv[0][0];
    int b = argv[0][1];

    while ((a >= 0) &&
           (a < b))
    {
        printf("a = %d\n", a);
        a++;
    }

    return 0;
}

和我与 GCC-4.5 -02 -Wstrict溢出= 5

编译器对我大喊大叫
警告:假设符号溢出时不发生变化的X + - C1 C2 CMP与X CMP C1 + - C2

这是什么意思是什么呢?

What does this mean exactly?

如果我是正确的,该循环将永远不会导致溢出,因为对于一个要递增,它必须是比另一个整数小。如果是大,循环被终止。

If i am correct, this loop will never cause an overflow, because for a to be incremented, it must be smaller than another integer. If it is bigger, the loop is terminated.

任何人都可以解释这种现象对我?

Can anyone explain this behavior to me?

推荐答案

C ++标准说,如果有符号整数计算产生的再presentable范围之外的结果,该类型则行为是不确定的。整数溢出UB。一旦UB已经发生,实现可以自由地为所欲为。

The C++ standard says that if a signed integer calculation produces a result outside the representable range for the type then the behaviour is undefined. Integer overflow is UB. Once UB has happened, the implementation is free to do whatever it likes.

许多编译器适用于明确的假设,即UB不会发生的优化。 [或者,如果是这样,code可能是错误的,但它是你的问题!]

Many compilers apply optimisations on the explicit assumption that UB does not happen. [Or if it does, the code could be wrong but it's your problem!]

这编译器通知您,它是采用这样的优化来计算它无法从分析code,它UB不发生才能确定。

This compiler is notifying you that it is applying such an optimisation to a calculation where it is unable to determine from analysing the code that UB does not happen.

您一般的选择是:


  1. 让自己满足的UB不可能发生,而忽视了警告。

  2. 允许UB发生,并承担后果。

  3. 重写code使UB真的不能发生,编译器知道这不可能发生,并警告应该消失。

我推荐的最后一个选项。简单的测试范围 A B 应该是足够了。

I would recommend the last option. Simple range tests on a and b should be good enough.

我的猜测是,由于具有完全未知值循环交易,它是无法分析数据流不够好摸出UB能否发生与否,编译器会发出此错误。

My guess is that the compiler emits this error because the loop deals with completely unknown values, and it is unable to analyse the data flow well enough to work out whether UB can happen or not.

我们用我们卓越的推理能力,能说服自己,UB是不可能发生的,所以我们可以忽略的错误。事实上的错误信息仔细阅读可能会离开我们,询问是否是相关的。在哪里这两个恒定值 C1 C2

We with our superior reasoning power can convince ourselves that UB cannot happen, so we can ignore the error. In fact a careful reading of the error message might leave us asking whether it is relevant at all. Where are these two constant value C1 and C2?

我们也可以注意到, A 从来不能否定的,那么,为什么在循环测试?我可能会改写code共进晚餐preSS的错误,(但是从经验,可以成为一个弄巧成拙的锻炼)。试试这个,看看会发生什么(和避免不必要的混乱插句):

We might also note that a can never go negative, so why is that test in the loop? I would probably rewrite the code to suppress the error, (but from experience that can be a self-defeating exercise). Try this and see what happens (and avoid unneeded parenthetic clutter):

if (a >= 0) {
  while (a < b) {
    ...
    ++a;
  }
}

这篇关于C ++ while循环优化工作不正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-12 23:36