gpt4 book ai didi

c - GCC 不会就转换和数据丢失发出警告

转载 作者:行者123 更新时间:2023-12-03 15:46:30 24 4
gpt4 key购买 nike

我在 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 中,其中说:

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. 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. Therefore, it shouldn't be enabled if it is not explicitly requested.

关于c - GCC 不会就转换和数据丢失发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31055376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com