Why doesn't g++ -Wconversion warn about conversion of double to long int when double is constant?

老子叫甜甜 提交于 2021-02-09 07:11:13

问题


If I pass a double to a function requiring long, g++ warns of conversion problem, but if I pass a const double to a function requiring long, g++ is happy. The warning is the following:

warning: conversion to ‘long int’ from ‘double’ may alter its value [-Wconversion]

I would like g++ to give me a warning whether I pass a double or a const double. How would I do so?

I have makefile and some code you can run. I like to turn on as many warnings as I can, but perhaps one is implicitly shutting off another? I'm not sure.

Here's the Makefile:

WARNOPTS=-Wall -Wextra -pedantic \
      -Wdouble-promotion -Wformat=2 -Winit-self \
      -Wmissing-include-dirs -Wswitch-default -Wswitch-enum \
      -Wundef -Wunused-function -Wunused-parameter \
      -Wno-endif-labels -Wshadow \
      -Wpointer-arith \
      -Wcast-qual -Wcast-align \
      -Wconversion \
      -Wsign-conversion -Wlogical-op \
      -Wmissing-declarations -Wredundant-decls \
      -Wctor-dtor-privacy \
      -Wnarrowing -Wnoexcept -Wstrict-null-sentinel \
      -Woverloaded-virtual \
      -Wsign-compare -Wsign-promo -Weffc++


BUILD := develop
cxxflags.develop := -g $(WARNOPTS)
cxxflags.release := 
CXXFLAGS := ${cxxflags.${BUILD}}

foo: foo.cpp
    g++ $(CXXFLAGS) -o $@ $^

Here's foo.cpp:

// foo.cpp

#include <iostream>
#include <string>

using namespace std;

const double WAITTIME = 15;  // no warning on function call
//double WAITTIME = 15;  // warning on function call

bool funcl( long time);


bool funcl( long time ) {
  cout << "time = " << time << endl;
  return true;
}





int main() {
  string rmssg;

  funcl( WAITTIME );
  return 0;
}

This is the version of g++ that I am using:

g++ --version
g++ (Debian 4.7.2-5) 4.7.2

Thanks for the help!


回答1:


This looks like a design decision by gcc if we look at the Wconversion wiki, it says:

[...]The option should not warn for explicit conversions or for cases where the value cannot in fact change despite the implicit conversion.

If we look at the assembly for this code we can see gcc is actually using a constant value of 15 instead of a variable which means it is also performing constant folding as well.



来源:https://stackoverflow.com/questions/24677505/why-doesnt-g-wconversion-warn-about-conversion-of-double-to-long-int-when-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!