Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC does not warn about conversion and loss of data

Tags:

c

gcc

mingw

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?

like image 605
Saeid Yazdani Avatar asked Jun 25 '15 16:06

Saeid Yazdani


1 Answers

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.

like image 179
Shafik Yaghmour Avatar answered Nov 14 '22 21:11

Shafik Yaghmour