C ++ for循环中的无符号整数 [英] Unsigned integers in C++ for loops

查看:188
本文介绍了C ++ for循环中的无符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了一些关于在C ++中使用无符号整数而不是有符号整数的循环的Stackoverflow的研究。但我仍然不明白为什么有一个问题(请参阅无符号整数反向迭代for循环)。为什么下面的代码会产生分段错误?

  #include< vector> 
#include< iostream>
使用namespace std;

int main(void)
{
vector< double> X(10); (unsigned int i = 9; i> = 0; i--)
$ b {
cout< i =<<我 ENDL;
x [i] = 1.0;
}

cout<< x0 =<< x [0]<< ENDL;

返回0;



$ b我知道问题是当索引i等于零因为有像溢出一样的东西。但是我认为一个无符号整数可以取零值,不是吗?现在,如果我用一个有符号的整数替换它,这是绝对没有问题的。

有人可以用无符号整数解释反向循环背后的机制吗?



非常感谢!

解决方案

这里的问题是一个无符号整数因此,循环测试:

   i> = 0 

将始终为真。因此你得到一个无限循环。

当它下降到零以下时,它包装到最大值 unsigned 值。


因此,您还将访问 x [i] 超出界限。 p>

对于带符号整数,这不是一个问题,因为它会简单地为负数,从而失败 i> = 0 / p>

因此,如果您想使用无符号整数,您可以尝试以下其中一种方法:

  for(unsigned int i = 9; i--!= 0;)



< (unsigned int i = 9; i!= -1; i--)




这两个是由GManNickG和AndreyT从评论中提出的。




这里是我原来的3个版本:

$ p $ for(unsigned int i = 9 ; i!=(unsigned)0 - 1; i--)

  for(unsigned int i = 9; i!=〜(unsigned)0; i--)

或者

  for(unsigned int i = 9; i!= UINT_MAX; i--)


I have made some research on Stackoverflow about reverse for loops in C++ that use an unsigned integer instead of a signed one. But I still do NOT understand why there is a problem (see Unsigned int reverse iteration with for loops). Why the following code will yield a segmentation fault?

#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
    vector<double> x(10);

    for (unsigned int i = 9; i >= 0; i--)
    {
        cout << "i= " << i << endl;
        x[i] = 1.0;
    }

    cout << "x0= " << x[0] << endl;

    return 0;
}

I understand that the problem is when the index i will be equal to zero, because there is something like an overflow. But I think an unsigned integer is allowed to take the zero value, isn't it? Now if I replace it with a signed integer, there is absolutely no problem.

Does somebody can explain me the mechanism behind that reverse loop with an unsigned integer?

Thank you very much!

解决方案

The problem here is that an unsigned integer is never negative.

Therefore, the loop-test:

i >= 0

will always be true. Thus you get an infinite loop.

When it drops below zero, it wraps around to the largest value unsigned value.
Thus, you will also be accessing x[i] out-of-bounds.

This is not a problem for signed integers because it will simply go negative and thus fail i >= 0.

Thus, if you want to use unsigned integers, you can try one of the following possibilities:

for (unsigned int i = 9; i-- != 0; )

and

for (unsigned int i = 9; i != -1; i--)

These two were suggested by GManNickG and AndreyT from the comments.


And here's my original 3 versions:

for (unsigned int i = 9; i != (unsigned)0 - 1; i--)

or

for (unsigned int i = 9; i != ~(unsigned)0; i--)

or

for (unsigned int i = 9; i != UINT_MAX; i--)

这篇关于C ++ for循环中的无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆