简体   繁体   English

C:警告隐式long to int转换

[英]C: warns about implicit long to int conversion

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. 我想知道是否有一种方法可以告诉编译器(我在gcc版本4.1.2 20080704(Red Hat 4.1.2-46)或icc 11.1上)在每次长到内隐式转换时都会发出警告地点。 For example, compiling the file test.c which contains the code: 例如,编译包含代码的文件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

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. 因为数字12345678901溢出了int而不是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. 意外的-Wconversion选项(对我而言)不会这样做。

Thanks, 谢谢,

Michele 米歇尔

Check if your gcc version has -Wshorten-64-to-32 . 检查您的gcc版本是否具有-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. 编辑:我认为shorten-64-to-32可能是苹果的延伸,主线永远不会捡到,可悲的是。 So you may be out of luck unless you upgrade to gcc-4.3 or higher. 所以除非你升级到gcc-4.3或更高版本,否则你可能会失败。

-Wconversion的行为随-Wconversion 改变 - 更新你的编译器并再试一次(不能检查它是否真的有效,因为我在32位系统上,但是因为正确地为atoll发出警告,它应该)。 ..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM