[英]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
啟用它,所以在鏈接的Wiki中對此進行了介紹,該維基說:
隱式轉換在C語言中非常常見。這與前端中沒有數據流(請參閱下一個問題)的事實相關,導致難以避免出現警告,提示代碼無法正常工作和有效。 Wconversion是為特定用途設計的(安全審核,將32位代碼移植到64位等),程序員願意接受並解決無效警告。 因此,如果未明確請求,則不應啟用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.