Question

I'm reading Stroustrup's newest C++ book (4th edition) and the following example from the book doesn't throw an error.

#include <iostream>
using namespace std;

int main(const int argc, const char* argv[]) {

  // Narrowing conversion.
  // According to Stroustrup, an error should happen here
  // because the curly-brace-delimited initializer 
  // saves us from conversions that lose information.
  // But after compiling and running the code the output is 7.
  int i2 {7.2};
  cout << i2 << endl;

  return 0;
}

I'm using the following command to compile the code on a Gentoo system. (g++ version: 4.6.3)

g++ -std=c++0x -o output input.cpp

Why doesn't it throw an error?

Was it helpful?

Solution

A more current version of gcc (4.8.1), treats this as a warning:

trash9.cpp: In function 'int main(int, const char**)':
trash9.cpp:11:14: warning: narrowing conversion of '7.2000000000000002e+0' from
'double' to 'int' inside { } [-Wnarrowing]
   int i2 {7.2};

The standard requires that the compiler issue a "diagnostic", so (with the right documentation) this undoubtedly qualifies. The compiler is free to continue compiling the code afterwards.

VC++ does closer to what you apparently want:

trash9.cpp(11) : error C2397: conversion from 'double' to 'int' requires a narro
wing conversion
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top