CKTIS / C++
Type conversion
Type conversion adapts an expression to a required type. Learn implicit conversions, explicit static_cast conversions, integral promotions, and discarding a value with a cast to void.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
T value = expression; static_cast<T>(expression); static_cast<void>(expression); (void)expression;Type conversion lets an expression be used as an expression of another type. Implicit conversions occur during initialization, argument passing, and operator evaluation, among other contexts. An explicit conversion can be written as static_cast<T>(expression). A cast does not change an existing variable's declared type.
Integral promotions preserve values: short converts to int; unsigned short converts to int if that type represents the entire source range, otherwise to unsigned int. bool converts to int, with false becoming 0 and true becoming 1. Certain character types, bit-fields, and unscoped enumerations have separate rules. In the example, unary + promotes small to int.
Not every conversion preserves the value. Floating-to-integer conversion discards the fractional part toward zero: static_cast<int>(3.75) produces 3. If the truncated result cannot be represented by the destination type, behavior is undefined. An explicit cast does not provide a range check.
A cast to void, written as static_cast<void>(expression) or (void)expression, explicitly discards an expression's value without removing its side effects. Thus, static_cast<void>(++calls) still increments calls; this is not a pointer conversion to void*.
The example uses features available in C++23. The supplied source is an evolving working draft, not a frozen C++23 text. A repository compiler flag does not attest the production runtime version.
Examples
#include <iostream>
#include <type_traits>
int main() {
short small = 7;
auto promoted = +small;
static_assert(std::is_same_v<decltype(promoted), int>);
double exact = promoted;
int truncated = static_cast<int>(3.75);
int calls = 0;
static_cast<void>(++calls);
std::cout << promoted << ' ' << exact << ' '
<< truncated << ' ' << calls << '\n';
}
Result
7 7 3 1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.