当double为常数时,为什么g ++ -Wconversion不警告将double转换为long int? [英] Why doesn't g++ -Wconversion warn about conversion of double to long int when double is constant?

查看:74
本文介绍了当double为常数时,为什么g ++ -Wconversion不警告将double转换为long int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]

我希望g ++给我一个警告,无论我通过double还是const double.我该怎么办?

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

我有makefile和一些可以运行的代码.我喜欢打开尽可能多的警告,但是也许一个隐式关闭了另一个警告?我不确定.

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.

这是Makefile:

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 $@ $^

这是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 ++版本:

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

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

感谢您的帮助!

推荐答案

如果我们查看

[...]对于显式转换或案例,不应警告该选项即使进行隐式转换,该值实际上也无法更改.

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

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

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.

这篇关于当double为常数时,为什么g ++ -Wconversion不警告将double转换为long int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆