Home > Enterprise >  Why there is no compilation error when static_cast float to int?
Why there is no compilation error when static_cast float to int?

Time:11-12

What will happen when you execute this code snippet?

#include <iostream>

int main() {
   float a = 5.51;
   int b = static_cast<int>(a);
   std::cout << b;
}

Correct answer is:

5 will be printed on standard output, with no compilation warnings generated.

But for me would make more sense to generate compilation warning as precision would be lost. Why not?

CodePudding user response:

I think it depends on compiler level of warning. In my case with Visual Studio 2022 and level warnings set to lvl 4, I get the following warning:

Warning C4305 'init': truncation from 'double' to 'float'.

CodePudding user response:

As commented by @wohlstad:

The explicit cast tells the compiler you did the conversion intenionally, and therefore there's no need for a warning. Most compiler will issue a warning if you assign a float to an int without a cast.

  •  Tags:  
  • c
  • Related