﻿# Explicit type casting

C and C\+\+ are languages that have weak static typing\. **Static** means that types are known at compile time, and **weak** means that languages enable different types to be mixed in the same expression and perform implicit conversions\.

Despite the presence of implicit conversions, many operations require explicit type casting\. To perform explicit type casting, special programming language constructs are used\. They specify how to handle the type of a particular variable or expression\.

Let's look at the main types of type casts in C and C\+\+\.

## const\_cast

The _const\_cast_ operator is used in C\+\+ to add or remove _const_ and/or _volatile_ qualifiers\. Example:

```cpp
const_cast<new_type>(expression)
```

## static\_cast

The _static\_cast_ operator is used in C\+\+ for type conversion at compile time\. If the conversion fails, a compilation error is issued\. General view:

```cpp
static_cast<new_type>(expression)
```

## dynamic\_cast

The _dynamic\_cast_ conversion operator is used in C\+\+ for polymorphic type conversion at runtime\.

Example:

```cpp
dynamic_cast<new_type>(expression)
```

If conversion is impossible, two scenarios can occur:

* if the resulting type is a pointer, the result of the expression is a null pointer;
* if the resulting type is a reference, an exception of the [_std::bad\_cast_](https://en.cppreference.com/w/cpp/types/bad_cast) type is thrown\. 

## reinterpret\_cast

The _reinterpret\_cast_ operator is used in C\+\+ to cast incompatible types based on their bit representation\. For example, we can convert an integer to a pointer and vice versa\. Example:

```cpp
reinterpret_cast<new_type>(expression)
```

## C\-style cast

To cast an expression of any type to any other data type \(with a few exceptions\), use the C\-style operator\. Even though you can use it in C\+\+, it is a bad practice since it becomes much easier to make a mistake\. Example:

```cpp
(new_type) expression
```

**Sources**

1. [CppReference\. C\+\+ Explicit type conversion](https://en.cppreference.com/w/cpp/language/explicit_cast)
1. [CppReference\. C cast operator](https://en.cppreference.com/w/c/language/cast)