2

This code works fine:

    double a =2.12345;
    int b{a};            // According to primer error: narrowing conversion required
    int c(a);            //This is fine

Is it something which I am missing? For me when a float/double is assigned to int the values on left of the decimal are printed (floor value). Primer says error.

Gaurav
  • 201
  • 1
  • 11
  • 1
    related: https://stackoverflow.com/questions/4434140/narrowing-conversions-in-c0x-is-it-just-me-or-does-this-sound-like-a-breakin – RHertel Nov 12 '17 at 10:20
  • 2
    Try building it with `g++ -std=c++14` so you don't get the gnu++14 extensions. – Jesper Juhl Nov 12 '17 at 10:41

2 Answers2

4

Is it something which I am missing?

The unfortunate detail of compilers deviating from the standard. GCC doesn't enforce it unless you tell it that it should. Try compiling with the -pedantic-errors option.

The primer isn't wrong, it's an ill-formed program according to the C++ standard alone. But compilers may choose to accept it as an extension, such is what GCC does.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
0

Some compilers (rightfully) enforce it by default. MacOSX clang for example would return an error:

type 'double' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing]

For GCC, the option -Wconversion should generate a warning.

Visiedo
  • 377
  • 5
  • 9