C:警告隐式 long 到 int 转换
我想知道是否有办法告诉编译器(我使用的是 gcc 版本 4.1.2 20080704 (Red Hat 4.1.2-46) 或 icc 11.1)在 long 到 int 隐式转换时抛出警告地方。例如,编译包含以下代码的文件 test.c
:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
int n = atol(argv[1]);
printf("int: %d\n", n);
long int N = atol(argv[1]);
printf("long: %ld\n", N);
return 0;
}
with:
gcc -Wall -Wconversion test.c -o test
不会产生任何警告。 运行生成的二进制文件
./test 12345678901
正如我所预期的那样,
int: -539222987
long: 12345678901
:数字 12345678901 已溢出 int,但未溢出 long。 我希望编译器在发生类似情况时告诉我。选项 -Wconversion 出乎意料地(对我来说)不会这样做。
谢谢,
米歇尔
I was wondering whether there is a way to tell the compiler (I'm on gcc version 4.1.2 20080704 (Red Hat 4.1.2-46) or icc 11.1) to throw a warning whenever a long-to-int implicit conversion takes place. For example, compiling the file test.c
which contains the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
int n = atol(argv[1]);
printf("int: %d\n", n);
long int N = atol(argv[1]);
printf("long: %ld\n", N);
return 0;
}
with:
gcc -Wall -Wconversion test.c -o test
does not produce any warnings. Running the resulting binary as
./test 12345678901
I get, as expected:
int: -539222987
long: 12345678901
as the number 12345678901 has overflown the int but not the long.
I'd like the compiler to tell me whenever something like this might happen. The option -Wconversion unexpectedly (to me) does not do that.
Thanks,
Michele
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
检查您的 gcc 版本是否有
-Wshorten-64-to-32
。做好应对可能出现的大量虚假双倍的准备 ->如果您在代码中使用浮点,则会出现浮点转换警告。编辑:我认为
shorten-64-to-32
可能是主线从未采用的Apple扩展,遗憾的是。因此,除非升级到 gcc-4.3 或更高版本,否则您可能会运气不佳。Check if your gcc version has
-Wshorten-64-to-32
. Be prepared for a deluge of possibly spurious double -> float conversion warnings if you use floating-point in your code.edit: I think
shorten-64-to-32
may be an Apple extension that mainline never picked up, sadly. So you may be out of luck unless you upgrade to gcc-4.3 or higher.尝试 gcc 4.3.0
http://gcc.gnu.org/wiki/NewWconversion
Try gcc 4.3.0
http://gcc.gnu.org/wiki/NewWconversion
-Wconversion
GCC4.3 的行为发生了变化 - 更新你的编译器并重试(无法检查它是否真的有效,因为我在 32 位系统上,但随着atoll
正确发出警告,它应该)...The behaviour of
-Wconversion
changed with GCC4.3 - update your compiler and try again (can't check if it really works myself as I'm on a 32bit system, but as the warning gets correctly emitted foratoll
, it should)...