C++ static_cast
Date: 2023-02-20Last modified: 2024-11-02
Table of contents
::: important Prefer C++ casts over C- style casts
- C++ casts,
static_cast<>
is jut one of them, make your intent very clear - They are easy to search for in code
static_cast<>()
is checked by the compiler, and if the types are not
double x{12.5};
double y{34.6};
unsigned char cc[] = {0, 0, 0, 0};
auto sum1 = static_cast<int>(x) + static_cast<int>(y);
auto sum2 = static_cast<int>(x + y);
fmt::print("sizeof(sum1) = {} sum1 = {} <- (12+34)\n", sizeof(sum1), sum1);
fmt::print("sizeof(sum2) = {} sum2 = {} <- (47.1)\n", sizeof(sum2), sum2);
fmt::print("{} {} {} {} {}\n", static_cast<int>(*cc), cc[0], cc[1], cc[2],
cc[3]);
cc[1] = 254; // this does not affect the static_cast below
fmt::print("{} {} {} {} {}\n", static_cast<int>(*cc), cc[0], cc[1], cc[2],
cc[3]);
cc[0] = 14;
fmt::print("{} {} {} {} {}\n", static_cast<int>(*cc), cc[0], cc[1], cc[2],
cc[3]);
fmt::print("Buffer overflow\n");
unsigned char c = 253;
for (int i = 0; i < 5; ++i) {
fmt::print("i: {} -> {}\n", i, static_cast<int>(++c));
}
fmt::print("Buffer underflow\n");
for (int i = 0; i < 5; ++i) {
fmt::print("i: {} -> {}\n", i, static_cast<int>(--c));
}
Possible output
sizeof(sum1) = 4 sum1 = 46 <- (12+34)
sizeof(sum2) = 4 sum2 = 47 <- (47.1)
0 0 0 0 0
0 0 254 0 0
14 14 254 0 0
Buffer overflow
i: 0 -> 254
i: 1 -> 255
i: 2 -> 0
i: 3 -> 1
i: 4 -> 2
Buffer underflow
i: 0 -> 1
i: 1 -> 0
i: 2 -> 255
i: 3 -> 254
i: 4 -> 253