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
启用它,在链接的维基中有说明:
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.
我在 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
启用它,在链接的维基中有说明:
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.