简体   繁体   English

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

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

I was fiddling around with GCC 4.9.2 on windows and noticed it does not warn about conversion from double to int, while the visual studio compiler does: 我在Windows上摆弄GCC 4.9.2时,发现它没有警告从double到int的转换,而Visual Studio编译器却这样做:

The code: 编码:

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;
}

I compiled using: 我编译使用:

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

I compiled the same code with visual studio compiler: 我使用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

What am I doing wrong? 我究竟做错了什么?

You need to use the -Wconversion flag, with that gcc warns: 您需要使用-Wconversion标志,并且gcc警告:

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

Why isn't it enabled with -Wall or -Wextra , is covered in the linked wiki which says: 为什么未使用-Wall-Wextra启用它,所以在链接的Wiki中对此进行了介绍,该维基说:

Implicit conversions are very common in C. This tied with the fact that there is no data-flow in front-ends (see next question) results in hard to avoid warnings for perfectly working and valid code. 隐式转换在C语言中非常常见。这与前端中没有数据流(请参阅下一个问题)的事实相关,导致难以避免出现警告,提示代码无法正常工作和有效。 Wconversion is designed for a niche of uses (security audits, porting 32 bit code to 64 bit, etc.) where the programmer is willing to accept and workaround invalid warnings. Wconversion是为特定用途设计的(安全审核,将32位代码移植到64位等),程序员愿意接受并解决无效警告。 Therefore, it shouldn't be enabled if it is not explicitly requested. 因此,如果未明确请求,则不应启用它。

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

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