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:
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:
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:
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With