How to declare and initialize C++ variables
Here are some examples showing different initialization methods:
double r(3.0); // Direct initialization
double s = 3.0; // Copy initialization
double t{3.0}; // List initialization (starting from C++11)
All three methods will create adouble
variable of type and initialize it to3.0
。
These three initialization methods are semantically different:
Direct initialization (double r(3.0);
):This method is called direct initialization in C++. It means creating a name calledr
ofdouble
Type variable and initialize it to3.0
. The syntax for direct initialization uses parentheses.
Copy Initialization (double s = 3.0;
):This is a traditional initialization method called copy initialization. It also means creating a name calleds
ofdouble
Type variable and initialize it to3.0
. In copy initialization, use the equal sign=
Assign value to variable.
List initialization (double t{3.0};
):This is a new initialization method introduced by C++11, also known as the initialization list. It uses curly braces{}
to initialize the variable. List initialization can not only be used for variable declarations, but also for arrays, structures, classes and other types. List initialization will be more stringent in some cases, such as checking for narrower conversions.
But in C++, there are some subtle differences between direct initialization and copy initialization. Generally, direct initialization is more efficient and can be used in more cases because it performs initialization operations while declaring.
In most cases, all three initialization methods can be used and they are equivalent in results. However, list initialization is more stringent in some cases and is checked when using narrower conversions, which makes it more secure in some cases.
Narrow conversion case:
double d = 10.5; int i = d; // Copy initialization, narrowing conversion, and may lose accuracyint j = {10.5}; // List initialization,Will cause a compilation error,Because narrowing conversion is not allowed
When copy initialization,Willdouble
Assign value of type toint
Variables of typei
, which results in narrowing conversions and may lose accuracy.
When list initialization,Will10.5
Give toint
Variables of typej
, This will also lead to narrower conversion, but list initialization checks for narrower conversion, which will therefore lead to compilation errors. The list initialization method is more stringent in this case to avoid narrower conversions that may lead to errors.
This is the end of this article about the declaration and initialization method of C++ variables. For more related declaration and initialization content of C++ variables, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!