gpt4 book ai didi

c - 如何修复 : "comparison between signed and unsigned"? 之类的警告

转载 作者:太空狗 更新时间:2023-10-29 16:35:26 24 4
gpt4 key购买 nike

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

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

我知道我可以解决这个问题的一种方法是关闭警告,但他们并没有让我使用这些设置来最终关闭它们。

另一种方法是强制转换,但有人告诉我强制转换已被弃用。

另外,我可以将 x 变成一个 unsigned int:

unsigned x;

但当我必须使用这些编译器选项比较有符号值和无符号值时,它并不能解决一般问题。有没有更清洁的方式来代替类型转换?

最佳答案

替换

int x;
/* ... */
for(x=0;x<sizeof(arr) / sizeof(int);x++)

通过

for(size_t x=0;x<sizeof(arr) / sizeof(int);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?

在这种情况下,尝试弄清楚带符号的数字是否可以有一个会导致溢出的值。如果没有,您可以忽略该警告。否则转换为无符号类型(如果它与有符号组件大小相同或更大)就足够了。

关于c - 如何修复 : "comparison between signed and unsigned"? 之类的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/859943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com