C / C ++使用int或unsigned int [英] C/C++ use of int or unsigned int

查看:184
本文介绍了C / C ++使用int或unsigned int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在很多代码示例,源代码,库等中。我看到使用int,就我所知,unsigned int会更有意义。

In a lot of code examples, source code, libraries etc. I see the use of int when as far as I can see, an unsigned int would make much more sense.

我看到的一个地方很多是中的循环。见下面的例子:

One place I see this a lot is in for loops. See below example:

for(int i = 0; i < length; i++)
{
    // Do Stuff
}

为什么你会使用int而不是unsigned int?只是懒惰 - 人们不能打扰未签名

Why on earth would you use an int rather than an unsigned int? Is it just laziness - people can't be bothered with typing unsigned?

推荐答案

使用 unsigned 会引入难以发现的编程错误,通常最好使用signed int 避免他们。一个例子是当你决定向后而不是向前迭代时写下这个:

Using unsigned can introduce programming errors that are hard to spot, and it's usually better to use signed int just to avoid them. One example would be when you decide to iterate backwards rather than forwards and write this:

for (unsigned i = 5; i >= 0; i--) {
    printf("%d\n", i);
}

如果你在循环中做一些数学计算,那就另外了:

Another would be if you do some math inside the loop:

for (unsigned i = 0; i < 10; i++) {
    for (unsigned j = 0; j < 10; j++) {
        if (i - j >= 4) printf("%d %d\n", i, j);
    }
}

使用 unsigned 介绍了这些类型的错误,并没有任何好处。

Using unsigned introduces the potential for these sorts of bugs, and there's not really any upside.

这篇关于C / C ++使用int或unsigned int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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