PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 16, 2022

[FIXED] Why is there no warning from -Wfloat-equal when comparing containers of doubles?

 July 16, 2022     c++, clang, floating-point, gcc-warning, warnings     No comments   

Issue

If I use the compiler option -Wfloat-equal with GCC or Clang, equality comparisons of float/double values cause a warning. However, when comparing containers (like std::vector or std::tuple) of float or double values, no such warning is raised.

Example code (also at https://godbolt.org/z/YP8v8hTs3):

#include <tuple>
#include <vector>
#include <assert.h>

int main() {
    double d = 1.2;

    std::tuple<double, double> t_d{1.2, 3.14};
    std::tuple<double, double> t_d_2{1.2, 3.14};

    std::vector<double> v_d{1.2, 3.14};
    std::vector<double> v_d_2{1.2, 3.14};

    // this causes a warning, like "warning: comparing floating-point with '==' or '!=' is unsafe [-Wfloat-equal]":
    assert(d == 1.2);
    // but why no warning from -Wfloat-equal here?
    assert(t_d == t_d_2);
    // no warning here either:
    assert(v_d == v_d_2);

    // all of these cause warnings as expected:
    assert(std::get<0>(t_d) == 1.2);
    assert(std::get<0>(t_d) == std::get<0>(t_d_2));
    assert(v_d[0] == 1.2);
    assert(v_d[0] == v_d_2[0]);

    return 0;
}

Why are the warnings omitted for these container comparisons? And more importantly, what can I do to actually get these warnings as well?


Solution

GCC doesn't report warnings for system headers by default. The desired behavior may be obtained by adding -Wsystem-header compiler flag.

Quotation from the documentation:

-Wsystem-headers

Print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, on the assumption that they usually do not indicate real problems and would only make the compiler output harder to read. Using this command-line option tells GCC to emit warnings from system headers as if they occurred in user code...

Live demo: https://godbolt.org/z/s6rExszj6

Clang seemingly adopted the same approach, see https://clang.llvm.org/docs/UsersManual.html#controlling-diagnostics-in-system-headers and https://clang.llvm.org/docs/UsersManual.html#options-to-control-error-and-warning-messages.

Live demo: https://godbolt.org/z/n9xY8rcM8



Answered By - Daniel Langr
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing