C:我该如何解决类似的警告:"符号和无符号&QUOT之间的比较; [英] C: how can I fix warnings like: "comparison between signed and unsigned"

查看:213
本文介绍了C:我该如何解决类似的警告:"符号和无符号&QUOT之间的比较;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在建议使用下列选项与海湾合作委员会,因为它有助于避免大量常见错误。它开启了一堆警告和-Werror把他们变成错误。

GCC -pedantic -W -Wall -Wextra -Wshadow -Wstrict溢出= 5 -Wwrite串-std = C99 -Werror

由于以下测试code:

 的#include<&stdio.h中GT;INT主要(无效)
{
    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));    为(X = 0; X&下;的sizeof(改编)/的sizeof(int);在X ++)
    {
    的printf(%d个\\ N,编曲[X]);
    }    返回0;
}

我得到这样的:

  test.c以11:错误:比较符号和无符号

我知道的一种方式,我可以解决这个问题被关闭的警告,但他们没有让我使用这些设置来关闭它们到底。

另一种方法是投了东西,但我被告知,铸造是pcated德$ P $。

另外,我可以使x转换成一个unsigned int:

 无符号X;

但是,当我不得不签值使用这些编译器选项无符号值进行比较并没有解决一般问题。是否有一个更清洁的方式insted的铸造?


解决方案

这真的取决于数据类型。有可能通过隐式铸造的值,以包含所有的符号和无符号类型的可用值的超一类型以避免这种情况。例如,你可以使用一个64位有符号值来比较无符号的32位和32位有符号值。

然而,这是一个极端例子,你需要做的操作,如验证类型的大小。你的最佳解决方案是使用相同类型的两个操作数。

如果必须转换,你认为你可能会造成溢出,并考虑如果这是你的应用程序的重要与否。

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

Given the following test code:

#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;
}

I get this:

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.

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 insted of casting?

解决方案

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.

这篇关于C:我该如何解决类似的警告:&QUOT;符号和无符号&QUOT之间的比较;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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