Narrowing conversions in C++ 11

The initialization-list syntax provides protection against narrowing, i.e.  it’s , against assigning a numeric value to a numeric type not capable of holding that value. Now  the C++11 standard is avoids a lot of incompatibilities is by relying on the actual values of initializers.

The problem of ordinary initialization in previously C/C++   it’s Implicit truncation
For example:

#include

void PrintValue (int y)
{
  std::cout << "the y = " << y <<"\n";
}

int main()
{
  int x = 36.6;
  std::cout << "the x = " << x <<"\n";

  PrintValue (34.13);

  return 0;
}

Output in g++-4.8 :
without_narrowing

However, in  C++11 avoids a lot of incompatibilities (initialization preventing narrowing) :

#include

void PrintValue (int y)
{
  std::cout << "the y = " << y <<"\n";
}

int main()
{
 int x = {36.6};
 std::cout << "the x = " << x <<"\n";

 PrintValue ({34.13});

 return 0;
}

Output in g++-4.8 :
with_narrowing
As we see, if we use initialization-list syntax,  the compiler “shouts” about  type conversions (that attempt to store values in a type “narrower” than the value)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s