如何解决类似“已签名和未签名之间的比较"之类的警告? [英] How can I fix warnings like: "comparison between signed and unsigned"?

查看:67
本文介绍了如何解决类似“已签名和未签名之间的比较"之类的警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建议我在GCC中使用以下选项,因为它有助于避免许多常见错误.它会打开一堆警告,而 -Werror 会将它们变成错误.

I have been advised to use the following options with GCC, as it helps to avoid a lot of common errors. It turns on a bunch of warnings and -Werror turns them into errors.

gcc -pedantic -W -Wall -Wextra -Wshadow -Wstrict-overflow=5 -Wwrite-strings -std=c99 -Werror

给出以下测试代码:

#include <stdio.h>

int main(void)
{
    int arr[8]={0,10,20,30,40,50,60,70};
    int x;

    printf("sizeof(arr): %d\n", sizeof(arr));
    printf("sizeof(int): %d\n", sizeof(int));

    for(x = 0; x < sizeof(arr)/sizeof(int); x++)
    {
        printf("%d\n",arr[x]);
    }

    return 0;
}

我明白了:

test.c:11: error: comparison between signed and unsigned

我知道可以解决此问题的一种方法是关闭警告,但它们并没有使我最终使用这些设置将其关闭.

I know that one way I can fix this is turning off the warnings, but they haven't made me use these settings to turn them off in the end.

另一种方法是强制转换内容,但有人告诉我不建议使用强制转换.

Another way is to cast the stuff, but I have been told that casting is deprecated.

此外,我可以将x设置为 unsigned int :

Also, I could make x into an unsigned int:

unsigned x;

但是当我必须使用这些编译器选项将带符号的值与无符号的值进行比较时,它不能解决一般问题.有没有一种更清洁的方法来代替铸造?

But it doesn't solve the general problem when I have to compare signed values with unsigned values using these compiler options. Is there an cleaner way instead of casting?

推荐答案

这实际上取决于数据类型.可以通过将值隐式转换为包含有符号和无符号类型中所有可用值的超集的类型来避免这种情况.例如,您可以使用一个64位带符号的值来比较一个无符号的32位和一个带符号的32位值.

This really depends on the data type. It is possible to avoid this by implicitly casting the values to a type which contains a superset of all the values available in the signed and unsigned type. For instance you could use a 64 bit signed value to compare an unsigned 32 bit and a signed 32 bit value.

但是,这是一个极端情况,您需要执行诸如验证类型大小之类的操作.最好的解决方案是对两个操作数使用相同的类型.

However this is a corner case and you need to do operations like verify the size of your types. Your best solution is to use the same type for both operands.

如果必须强制转换,请务必考虑可能导致溢出,并考虑这是否对您的应用程序很重要.

If you must cast, do consider that you could be causing an overflow and consider if that is important to your application or not.

这篇关于如何解决类似“已签名和未签名之间的比较"之类的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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