简体   繁体   English

有符号/无符号比较和-Wall

[英]Signed / unsigned comparison and -Wall

I have recently started using the -Wall compiler switch in an attempt to improve the quality of my code. 我最近开始使用-Wall编译器开关,以提高代码质量。 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). 因为number1.array.size是无符号的(这是std :: vector上的size方法)。 Since the test in the loop is i >= 0, i has to be signed or it doesn't work. 由于循环中的测试是i> = 0,所以我必须签名或不起作用。 It seems I have three choices; 看来我有三个选择。 to refrain from using -Wall, to ignore the warning, or to introduce an ancillary element... 避免使用-Wall,忽略警告或引入辅助元素...

    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." “由于循环中的测试是i> = 0,所以我必须签名或不起作用。” Just change your test like this: 只需像这样更改测试:

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

Gives you the same value of i in the loop body. 在循环体内为您提供相同的i值。

使用“ size_t”进行尺寸相关的比较。

size_t i = 0;

First of all, assigning a signed number to an unsigned type could have quite serious consequences (-1 in a signed 32-bit type is 4 294 967 295 in an unsigned), which is one of the reasons for that warning existing. 首先,将带符号的数字分配给无符号的类型可能会产生非常严重的后果(带符号的32位类型的-1为无符号的4 294 967 295),这是该警告存在的原因之一。 You do the conversion in one place or the other in both solutions, and no matter which of them you use, you would get the same effect by just casting size() to a signed integer. 您可以在两个解决方案中的一个位置或另一个位置进行转换,并且无论使用哪种方法,只要将size()转换为有符号整数,都将获得相同的效果。

Something along these lines would eliminate the vulnerability (not checked for correctness) 遵循这些原则可以消除漏洞(不检查其正确性)

for(unsigned int i=0;i<start;i++)
{
if(start-i>number1.array.size()) one_value=0;
}

I think :) 我认为 :)

You could try: 您可以尝试:

unsigned int i;

for (i = start; i > 0; )
{

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

}

This should work the same as your code - 这应该与您的代码相同-
i runs from start to 1 (instead of start-1 to 0 ), and the test for the array size was changed accordingly. istart1 (而不是start-10 )运行,并且对数组大小的测试也进行了相应更改。

unsigned int i;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM