我可以让 GCC 在将过宽的类型传递给函数时发出警告吗? [英] Can I make GCC warn on passing too-wide types to functions?

查看:31
本文介绍了我可以让 GCC 在将过宽的类型传递给函数时发出警告吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一些明显有缺陷的代码,我认为编译器应该对其进行诊断.但是 gccg++ 都没有,即使有我能想到的所有警告选项: -pedantic -Wall -Wextra

Following is some obviously-defective code for which I think the compiler should emit a diagnostic. But neither gcc nor g++ does, even with all the warnings options I could think of: -pedantic -Wall -Wextra

#include <stdio.h>

short f(short x)
{
    return x;
}

int main()
{
    long x = 0x10000007;   /* bigger than short */
    printf("%d
", f(x));  /* hoping for a warning here */
    return 0;
}

有没有办法让 gccg++ 对此发出警告?附带说明一下,您是否有另一个编译器在默认情况下或在相当常见的额外警告配置中对此发出警告?

Is there a way to make gcc and g++ warn about this? On a side note, do you have another compiler which warns about this by default or in a fairly common extra-warnings configuration?

注意:我使用的是 GCC(C 和 C++ 编译器)版本 4.2.4.

Note: I'm using GCC (both C and C++ compilers) version 4.2.4.

我刚刚发现 gcc -Wconversion 可以解决问题,但 g++ 的相同选项却没有,而且我真的在这里使用 C++,所以我需要 g++ 的解决方案(现在想知道为什么 -Wconversion 似乎不是这样).

I just found that gcc -Wconversion does the trick, but the same option to g++ doesn't, and I'm really using C++ here, so I need a solution for g++ (and am now wondering why -Wconversion doesn't seem to be it).

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34389 建议这可能会在 g++ 4.4 中得到修复...也许?我还不清楚它是否是同一个问题和/或修复是否真的出现在那个版本中.也许有 4.3 或 4.4 的人可以试试我的测试用例.

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34389 suggests that this may be fixed in g++ 4.4...maybe? It's not clear to me yet if it's the same issue and/or if the fix is really coming in that version. Maybe someone with 4.3 or 4.4 can try my test case.

推荐答案

使用 -Wconversion -- 问题是调用函数 f(short x) 时从 long x 到 short 的隐式转换(转换)[不是 printf],并且 -Wconversion 会说从长转换为短可能会改变值".

Use -Wconversion -- the problem is an implicit cast (conversion) from long x to short when the function f(short x) is called [not printf], and -Wconversion will say something like "cast from long to short may alter value".

..

刚刚看到你的笔记.-Wconversion 对我产生警告,在 Linux 上使用 g++ 4.3.2...(在 Debian 上使用 4.3.2-1)

just saw your note. -Wconversion results in a warning for me, using g++ 4.3.2 on Linux... (4.3.2-1 on Debian)

这篇关于我可以让 GCC 在将过宽的类型传递给函数时发出警告吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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