0

The following code compiles and executed without any issues. I would have the compiler (GCC 9.2.0) expected to prevent me from this, but it doesn't. Can anyone point out the background of this effect to me?

#include <iostream>

const double c = 1.23456789;

void print(float f)
{
    std::cout << (f == c) << std::endl;
}


int main()
{
    double d=1.23456789;
    print(d);
    std::cout << (d == c) << std::endl;
    return 0;
}

output (making clear that some implicit cast took place)

0
1
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Markus Dutschke
  • 9,341
  • 4
  • 63
  • 58
  • 1
    Side note: If you crank up the warning level (or turn it on explicitly) you can get a warning from most compilers about implicit conversions. Example: https://godbolt.org/z/39sddjfz8 – user4581301 Sep 01 '21 at 16:01
  • 2
    You can read all about _implicit conversions_ [here](https://en.cppreference.com/w/cpp/language/implicit_conversion). Specifically, [floating point conversions](https://en.cppreference.com/w/cpp/language/implicit_conversion#Floating-point_conversions). – Drew Dormann Sep 01 '21 at 16:03
  • @DrewDormann thanks. My example is mentioned as `numeric conversion`, I guess. – Markus Dutschke Sep 01 '21 at 16:06
  • @user4581301 you should write this as an answer. Adding `-Wconversion` to my compiler flags made clear very quickly, why this is not active by default. – Markus Dutschke Sep 01 '21 at 16:10
  • It's not a default because in many programs you would get a storm of conversion warnings that no one cares about the vast majority of the time. I usually just turn it on for safety critical code. – user4581301 Sep 01 '21 at 16:18
  • 1
    You can disallow the conversion by adding `template void print(T);` which will cause a link error. Or `template void print(T) { static_assert(false, "you cannot print that"); }` for more immediate feedback. – Eljay Sep 01 '21 at 16:26

1 Answers1

1

Why can I pass a double for a flaot argument in a function

Because you're allowed to pass an argument as a parameter of different type into a function if there is an implicit conversion sequence from the argument type to the parameter type. Conversion from double to float is such implicit conversion.

I would have the compiler (GCC 9.2.0) expected to prevent me from this

The compiler wouldn't conform to the language if it prevented from compiling well-formed programs. You can ask the compiler to warn you in this case. The option to enable such warning in your compiler is -Wfloat-conversion

eerorika
  • 232,697
  • 12
  • 197
  • 326