为什么 g++ -Wconversion 不警告当 double 是常数时将 double 转换为 long int?
Why doesn't g++ -Wconversion warn about conversion of double to long int when double is constant?
如果向需要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
而不是变量,这意味着它也执行了常数折叠
相关文章:
- C++在数学计算中将double转换为int
- 错误:无法将"<lambda(double)>"转换为"double(*)(double)"
- 如何将 Java double[][] 转换为 C++ <vector<vector>> JNI?
- 将 std::vector<boost::optional<double>> 转换为 std::vector<double>
- 将 double* 转换为 std::vector<double> (C++)
- 无法将复数<double>转换为双精度
- "double(*)(string, double, double)"尝试传递函数C++时"double"转换错误
- 从 double* 转换为 int 会失去精度
- 从'double'转换为'int'需要缩小转换范围
- 错误:无法将参数“1”的“double*”转换为“double”,错误:数组下标的类型“double[double]”无
- C 编译器从Double转换为INT
- 将“ double*”转换为“ boost :: Any*”
- 警告 C4244:'argument':从 'double' 转换为"浮点数",可能会丢失数据 - C++
- 当我使用模板时,编译器无法将函数的返回类型从 double 转换为 int
- 将double转换为LSBF(小Endian)十六进制字符串
- JNI在将Java double转换为jdouble时出现问题
- 无法将double转换为字符串
- 警告 C4244:"参数":从"double"转换为"int",可能会丢失数据
- C++无法将'long double'转换为'long double*',因为参数'1'为"long
- 在C++中,将double转换为long的类型返回了不正确的值