对于无符号变量,0 - 1 + 1总是等于0吗?

时间:2017-05-19 13:22:45

标签: c++ increment undefined-behavior unsigned c++98

在以下代码的末尾,x始终等于0?或者它是未定义行为的一个例子?

unsigned long int x = 0;
--x;
++x;

注意:C ++ 98上下文。出于一些(好的)原因,我无法使用C ++ 11。

为什么会这个问题?

我必须通过一个容器,索引索引,删除一些元素。我想用以下内容实现它:

MyContainerWithoutIterators c;
//...
for(unsigned long int i = 0; i < c.size(); ++i)
{
  if(i_have_to_remove(c[i]))
  {
    c.removeAtIndex(i);
    --i; // counterbalance incrementation of the loop
  }
}

注意:我知道我可以执行以下操作,我只想知道是否可以使用以前的实现。

MyContainerWithoutIterators c;
//...
for(unsigned long int i = 0; i < c.size();)
{
  if(i_have_to_remove(c[i]))
    c.removeAtIndex(i);
  else
    ++i;
}

0 个答案:

没有答案
相关问题