有符号/无符号比较和-Wall [英] Signed / unsigned comparison and -Wall

查看:224
本文介绍了有符号/无符号比较和-Wall的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用-Wall编译器开关,试图提高我的代码的质量。

  int i; 

for(i = start-1; i> = 0; i--)
{
if(i> = number1.array.size())
{
one_value = 0;
}

因为number1.array.size是无符号的::向量)。由于循环中的测试是i> = 0,我必须签名或不工作。看来我有三个选择;避免使用-Wall,忽略警告或引入辅助元素...

  int i; 
unsigned int j;

for(i = start-1; i> = 0; i--)
{
j =

if(j> = number1.array.size())
{
one_value = 0;
}

这些都不是特别可取的。

解决方案

因为测试在这个案件中应该做什么?循环是i> = 0,我必须签名或它不工作。只需更改您的测试,如下:

  for(unsigned i = start; i--;){
// ...
}

在循环体中给出相同的i值。 / p>

I have recently started using the -Wall compiler switch in an attempt to improve the quality of my code. It is giving (correctly) a warning about this little snippet...

    int i;

    for (i = start - 1; i >= 0; i--)
    {
        if (i >= number1.array.size())
        {
            one_value = 0;
        }

because number1.array.size is unsigned (it's the size method on a std::vector). Since the test in the loop is i >= 0, i has to be signed or it doesn't work. It seems I have three choices; to refrain from using -Wall, to ignore the warning, or to introduce an ancillary element...

    int          i;
    unsigned int j;

    for (i = start - 1; i >= 0; i--)
    {
        j = i;

        if (j >= number1.array.size())
        {
            one_value = 0;
        }

None of these seems particularly desirable. Can you suggest any alternative, or make a recommendation as to what I should do in this case?

解决方案

"Since the test in the loop is i >= 0, i has to be signed or it doesn't work." Just change your test like this:

for(unsigned i = start; i--;) {
    // ...
}

Gives you the same value of i in the loop body.

这篇关于有符号/无符号比较和-Wall的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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