longdouble ld = 3.1415926536;
int a{ld}, b = {ld}; // error: narrowing conversion required
int c(ld), d = ld; // ok: but value will be truncated
The compiler rejects the initializations of a and b because using a long double to initialize an int is likely to lose data. At a minimum, the fractional part of ld will be truncated. In addition, the integer part in ld might be too large to fit in an int
Note that the third version (with the curly braces) is valid C++11 but not valid C++98/C++03
int units_sold{0};
error C2470: 'units_sold' : looks like a function definition, but there is no
parameter list; skipping apparent body
Same with vlad from moscow's second version.
And vlad from moscow's first version isn't valid C++98/C++03 either, for a different reason.
error C2552: 'units_sold' : non-aggregates cannot be initialized with
initializer list
1> 'int' is not an array or class : Types which are not array or class
types are not aggregate
C++11 has tidied up the initialization syntax so it's nice and consistent!
long double ld = 3.1415926536;
int a{ld}, b = {ld}; // error: narrowing conversion required
int c(ld), d = ld; // ok: but value will be truncated
The compiler rejects the initializations of a and b because using a long double to initialize an int is likely to lose data. At a minimum, the fractional part of ld will be truncated. In addition, the integer part in ld might be too large to fit in an int
It means exactly that "The compiler rejects the initializations of a and b because using a long double to initialize an int is likely to lose data. At a minimum, the fractional part of ld will be truncated. In addition, the integer part in ld might be too large to fit in an int "
I am having trouble using the C++11 form of variable declaration and initialization on Visual Studio Express 2012. If I use the following code in VS Express, it fails but it works in DevC++:
int age{54};
I cannot figure out what I am doing wrong in VS Express. If I add the equal sign it works though...
Thanks Andy. I am working through the Stephen Prata book "C++ Primer Plus" - 6th edition. I will use the DevC++ as my primary learning tool but I also intend to "try" out my coding use Visual C++ too just to stay familiar withe the working of that IDE .
long double ld = 3.1415926536;
int b = {ld}; // error: narrowing conversion required
int d = ld; // ok: but value will be truncated
The latter syntax has been in the standard for quite a while and invokes implicit conversion. A decent compiler can warn you about such usage. They could have changed it, but there is always the legacy code to consider (although C++11 has a new auto too).
The former syntax is new. It cannot break old code, so it has the liberty to be different. More strict.