为什么 g++ -Wconversion 不警告当 double 是常数时将 double 转换为 long int?

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

本文关键字:double 转换 long int 常数时 -Wconversion g++ 警告 为什么      更新时间:2023-10-16

如果向需要long的函数传递双精度类型,g++会警告转换问题,但如果向需要long的函数传递const双精度类型,g++会很高兴。警告如下:

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

我希望g++在传递双精度类型还是const双精度类型时给我一个警告。我该怎么做呢?

我有makefile和一些代码你可以运行。我喜欢尽可能多地打开警告,但也许其中一个是在隐性地关闭另一个?我不确定。

下面是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 $@ $^

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;
}

这是我正在使用的g++版本:

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

谢谢你的帮助!

这看起来像是gcc的设计决策如果我们看一下Wconversion wiki,它说:

[…该选项不应该对显式转换或case发出警告尽管进行了隐式转换,但该值实际上不能更改。

如果我们看一下这段代码的汇编,我们可以看到gcc实际上使用了常数值15而不是变量,这意味着它也执行了常数折叠