【问题标题】:Why doesn't g++ -Wconversion warn about conversion of double to long int when double is constant?当 double 为常量时,为什么 g++ -Wconversion 不警告将 double 转换为 long int?
【发布时间】:2014-08-31 21:14:43
【问题描述】:

如果我将 double 传递给需要 long 的函数,g++ 会警告转换问题,但如果我将 const double 传递给需要 long 的函数,g++ 会很高兴。警告如下:

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

我希望 g++ 给我一个警告,无论我传递的是 double 还是 const double。我该怎么做?

我有 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

感谢您的帮助!

【问题讨论】:

  • 如果你使用常量15.5,它会发出警告吗?我猜当传递 double 变量时,由于它不知道值是什么,它会发出警告。在您的情况下,它“知道”不会有任何截断并且不会抱怨。
  • 推理可能与this case 非常相似,因为15 是一个文字常量表达式,编译器可以假设转换是否会溢出。
  • 我明白了。你们是对的。如果我将带有文字值的 const double 更改为 15.5,我会收到投诉。我没想过要尝试,因为在函数调用中它只是一个普通的 double 或 const double,对吗?无论如何,谢谢你帮助我。

标签: c++ gcc g++ implicit-conversion


【解决方案1】:

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

[...]该选项不应针对显式转换或大小写发出警告 尽管隐式转换,该值实际上不能改变。

如果我们查看此代码的程序集,我们可以看到 gcc 实际上使用常量值 15 而不是变量,这意味着它也在执行常量折叠。

【讨论】:

  • 谢谢!并感谢您的链接。我不知道 Wconversion 有自己的维基!! :)
猜你喜欢
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
  • 2015-08-23
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-10
相关资源
最近更新 更多