Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

differences between initializing int in c++ with double

what are the differences between this kind of initializing in c++;

int a = 0;
int a{};
int ();

why this code int a{3.14} get me error but this one int a = 3.14 or this one int a(3.14) do not

like image 824
Mohammad Abdollahzadeh Avatar asked Aug 06 '26 21:08

Mohammad Abdollahzadeh


1 Answers

It's called list initialization (C++11) :

int foo = 0; // Initialize foo with 0
int foo{}; // Initialize foo with foo's type (int) default value, which is 0
int foo(); // Function declaration

int bar = 5.f; // Initialize bar with 5 (narrowing conversion from floating point)
int bar{5.f}; // Doesn't compile, because there is a loss of data when casting a float to an int
int bar(5.f); // Initialize bar with 5 (narrowing conversion from floating point)

However :

float f{5}; // Okay, because there is no loss of data when casting an int to a float
like image 195
Jérémi Panneton Avatar answered Aug 09 '26 09:08

Jérémi Panneton