assignments - sluczak/cpp_by_example GitHub Wiki
Return to the previous lesson datatypes
Examples for this part available on git after calling the command:
git checkout -b origin casting
An =
(equals) character is a basic assignment operator in C++.
int a = 10;
float f = 20.0;
Current version of C++ standard (11), provide us with the new way of variable assignment with use of {
and }
(braces) initializer syntax.
This line:
int a = 10;
is identical with this line:
int a {10};
by using of types inferring, we can get the similar integer variable with usage of new auto
datatype.
auto a {10};
While for simple datatypes the "braces" initializer syntax doesn't have so much benefits, later we will see, that they emerge for more complex classes.
There are situations when we need to change the value type for purpose of some operation. While in most cases compiler is able to perform automatic casting of variable type, to assure the compatiblity, it is advised to "order" it from compiler explicitly.
To achieve this, we have to use the static_cast<T>()
or dynamic_cast<T>()
method.
At this moment we will limit to the
static_cast<T>(...)
only, whereT
is a type to cast.
For example
int i = 12;
double d = static_cast<double>(i);
will result in getting d = 12.0;
.
The notation of
<T>
belongs to the Templates area of C++. We will cover the templates topic further in training.
by using explicite type casting, we can avoid the potential risks of incorrect auto type-casting performed by compiler. A typical case of such mistake is shown below:
int a {10};
int b {2};
int c {3};
double d = ((a - b) / c); /// d = 2;
Programmer might assume that d
equals about 2.66667
, but because a - b
operation evaluates to int
type, compiler assumes that whole operation should result in integer value, therefore d == 2
.
In such situation, explicite type casting resolves the problem.
int a {10};
int b {2};
int c {3};
double d = (static_cast<double>(a - b) / c);
Now d
equals 2.66667
as desired.
Using of static_cast<T>()
is not always required, but should be considered everytime when programmer is not sure how compiler might resolve type casting.
C++ supports also a classic C-like casting. This type of casting is based on best-effort strategy and performs several casting strategy.
Because it is not capable of casting every type of types, it is advised to use it only on primitive numeric datatypes and use C++ like casting in every other situations.
double d = 12.2;
int i = (int)d; // i = 12;