【问题标题】:GCC does not warn about conversion and loss of dataGCC 不会就数据的转换和丢失发出警告
【发布时间】:2015-06-25 16:05:24
【问题描述】:

我在 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

我做错了什么?

【问题讨论】:

    标签: c gcc mingw


    【解决方案1】:

    您需要使用-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位等)程序员愿意接受的地方 和解决方法无效警告。因此,如果 没有明确要求。

    【讨论】:

    • 有趣,我认为/Wall 和或/Wextra 也会解决这个问题
    猜你喜欢
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多