繁体   English   中英

GCC不会警告转换和数据丢失

[英]GCC does not warn about conversion and loss of data

我在Windows上摆弄GCC 4.9.2时,发现它没有警告从double到int的转换,而Visual Studio编译器却这样做:

编码:

int main()
{   
    int celsius, fahrenheit, kelvin;
    celsius = 21;
    fahrenheit = celsius * 9 / 5 + 32;
    kelvin = celsius + 273.15; //here it should warn!

    printf("%d C = %d F = %d K", 
        celsius, fahrenheit, kelvin);

    return 0;
}

我编译使用:

gcc hello.c -Wall -Wextra -pedantic -std=c99

我使用Visual Studio编译器编译了相同的代码:

C:\temp>cl hello.c /nologo /W4 /FeC2f.exe
hello.c
hello.c(14): warning C4244: '=': conversion from 'double' to 'int', possible loss of data

我究竟做错了什么?

您需要使用-Wconversion标志,并且gcc警告:

warning: conversion to 'int' from 'double' may alter its value [-Wconversion]
 kelvin = celsius + 273.15; //here it should warn!

为什么未使用-Wall-Wextra启用它,所以在链接的Wiki中对此进行了介绍,该维基说:

隐式转换在C语言中非常常见。这与前端中没有数据流(请参阅下一个问题)的事实相关,导致难以避免出现警告,提示代码无法正常工作和有效。 Wconversion是为特定用途设计的(安全审核,将32位代码移植到64位等),程序员愿意接受并解决无效警告。 因此,如果未明确请求,则不应启用它。

暂无
暂无

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

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