为什么分配当一个符号立即无符号类型不GCC产生的警告? [英] Why doesn't GCC produce a warning when assigning a signed literal to an unsigned type?

查看:204
本文介绍了为什么分配当一个符号立即无符号类型不GCC产生的警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

若干问题揭示陷阱混合符号和无符号类型和大多数编译器似乎做好有关生成这种类型的警告时。然而,海湾合作委员会似乎并不关心时指定符号常为无符号类型!考虑下面的程序:

Several questions on this website reveal pitfalls when mixing signed and unsigned types and most compilers seem to do a good job about generating warnings of this type. However, GCC doesn't seem to care when assigning a signed constant to an unsigned type! Consider the following program:

/* foo.c */
#include <stdio.h>
int main(void)
{
    unsigned int x=20, y=-30;
    if (x > y) {
        printf("%d > %d\n", x, y);
    } else {
        printf("%d <= %d\n", x, y);
    }
    return 0;
}

编译使用GCC 4.2.1如下产生在控制台上无输出:

Compilation with GCC 4.2.1 as below produces no output on the console:

gcc -Werror -Wall -Wextra -pedantic foo.c -o foo

生成的可执行文件生成以下的输出:

The resulting executable generates the following output:

$ ./foo
20 <= -30

有一些原因,分配符号值时,GCC不会产生任何警告或错误信息 -30 的无符号整型变量ÿ

Is there some reason that GCC doesn't generate any warning or error message when assigning the signed value -30 to the unsigned integer variable y?

推荐答案

使用的 - Wconversion

~/src> gcc -Wconversion -Werror -Wall -Wextra -pedantic -o signwarn signwarn.c
cc1: warnings being treated as errors
signwarn.c: In function 'main':
signwarn.c:5: error: negative integer implicitly converted to unsigned type

我想这里的事情是,GCC实际上是pretty善于产生警告,但它默认为不这样做的(有时会有意想不到的)的情况。这是通过提供警告,浏览和选择的一组生成这些你觉得会帮助选择一个好主意。或者只是所有这些,和波兰的code,直到它的光芒! :)

I guess the thing here is that gcc is actually pretty good at generating warnings, but it defaults to not doing so for (sometimes unexpected) cases. It's a good idea to browse through the available warnings and choose a set of options that generate those you feel would help. Or just all of them, and polish that code until it shines! :)

这篇关于为什么分配当一个符号立即无符号类型不GCC产生的警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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