Take a look at boost's Numeric Conversion library. I think you'll need to define an overflow policy that truncates the source value to the target's legal range (but I haven't tried it). In all, it may take more code than your example above, but should be more robust if your requirements change.

Answer from Pontus Gagge on Stack Overflow
🌐
Learn C++
learncpp.com › cpp-tutorial › explicit-type-conversion-casting-and-static-cast
10.6 — Explicit type conversion (casting) and static_cast – Learn C++
March 4, 2025 - Using static_cast to make narrowing conversions explicit · Compilers will often issue warnings when a potentially unsafe (narrowing) implicit type conversion is performed. For example, consider the following snippet: int i { 48 }; char ch = i; // implicit narrowing conversion · Casting an int (2 or 4 bytes) to a char (1 byte) is potentially unsafe (as the compiler can’t tell whether the integer value will overflow ...
Discussions

static cast - C++ static_cast - safer way. why? - Stack Overflow
I have heard that static cast is a safer way to do casting. Lets say that I have the following code: int nValue = 48; char ch = nValue; This is implicit casting. But it is unsafe to change 4 byte... More on stackoverflow.com
🌐 stackoverflow.com
Newest 'static-cast' Questions - Stack Overflow
Stack Overflow | The World’s Largest Online Community for Developers More on stackoverflow.com
🌐 stackoverflow.com
c++ - How can I check whether a cast will result in overflow or underflow of the target type? - Stack Overflow
Is there a function in the Standard Library / Boost that will check whether a cast will result in overflow/underflow of the target type? For example: unsigned value = static_cast (... More on stackoverflow.com
🌐 stackoverflow.com
c++ - why does subtraction overflow with static_cast? - Stack Overflow
I understand that s1.size() - s2.size() underflows when s2 is bigger because it's subtraction of unsigned. Why casting one them to int doesn't result in integer subtraction? Why casting the whole t... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
gist.github.com › hugopeixoto › 0ea5589d320c39952a7b
checked static cast - checks during runtime if there is a value overflow/underflow when using static_cast · GitHub
checked static cast - checks during runtime if there is a value overflow/underflow when using static_cast - checked_static_cast.hpp
🌐
Stack Overflow
stackoverflow.com › questions › tagged › static-cast
Newest 'static-cast' Questions - Stack Overflow
In this function I static_cast this to a const pointer to a const B and ... ... I have two integers, m and k. The product of m and k might overflow an int datatype, so I used long long int data type but I was still getting runtime error: signed integer overflow: 89945 * 32127 ...
🌐
Forrestthewoods
forrestthewoods.com › blog › perfect_prevention_of_int_overflows
Perfect Prevention of Int Overflows - ForrestTheWoods
What floats, exactly, are safe to cast to an int. Solving empirically, the largest integer that can be exactly represented as a float is 2147483520 aka 2^31–128. The next floating point number after that is 2147483648f aka 2^31 which is just beyond the maximum int value of 2^31–13. What’s the final product look like? First, the float to int overflow.
Top answer
1 of 2
3

When you do

static_cast<int>(s1.size()) - s2.size()

You convert s1.size() to a int and then when you subtract s2.size() from it that int is promoted to the same type as s2.size() and then it is subtracted. This means you still have unsigned integer subtraction and since that can't ever be negative it will wrap around to a larger number. It is no different from doing s1.size() - s2.size().

You have the same thing with

static_cast<int>(s1.size() - s2.size())

With the added bonus of possible signed integer overflow which is undefined behavior. You are still doing unsigned integer subtraction so if s1 is smaller than s2 than you wrap around to a large number.

What you need to do is convert both s1.size() and s2.size() to a signed integer type to get singed integer subtraction. That could look like

static_cast<ptrdiff_t>(s1.size())  - static_cast<ptrdiff_t>(s2.size())

And now you will actually get a negative number if s1.size() is less than s2.size().


It should be noted that all of this can be avoided by using less than operator. Your function can be rewritten to be

bool isShorter(const string &s1, const string &s2)
{
    return s1.size() < s2.size();
}

which, IMHO, is much easier to read and understand.

2 of 2
2

Casting "one of them" to int leaves you with arithmetic operation that mixes string::size_type and int. In this mix the unsigned type has the same rank as int or higher, which means that the unsigned type still "wins": your int is implicitly converted back to string::size_type and the calculations are performed in the domain of string::size_type. Your conversion to int is effectively ignored.

Meanwhile, casting the result to int means that you are attempting to convert a value that does not fit into int's range. The behavior in such cases is implementation defined. In real-life 2's-complement implementations it is not unusual to see a simple truncation of the representation, which produces the "correct" result. This is not a good approach though.

If you want to perform this subtraction as a signed one, you have to convert both operands to signed types, making sure that the target signed type can represent both values.

(Theoretically, you can get away with converting just one operand to signed type, but for that you'd need to choose a type that can represent the entire range of string::size_type.)

Find elsewhere
🌐
Cppreference
en.cppreference.com › w › cpp › language › static_cast.html
static_cast conversion - cppreference.com
Safe downcast may be done with dynamic_cast. static_cast may also be used to disambiguate function overloads by performing a function-to-pointer conversion to specific type, as in
🌐
Stack Overflow
stackoverflow.com › tags › static-cast › info
'static-cast' tag wiki - Stack Overflow
Learn more about Teams · Get early access and see previews of new features. Learn more about Labs ... A C++ cast operator to convert from one type to another, using only information about the static type of the object being cast
🌐
Stack Overflow
stackoverflow.com › questions › 70135946 › overflow-check-for-static-cast-in-c
Overflow check for static_cast in c++ - Stack Overflow
November 27, 2021 - @Jundarer There are things called "overflow" and "underflow" for floating point, but those result in a loss of accuracy. If you don't care about loss of accuracy, you can simply limit your checks to when casting to integer types.
Top answer
1 of 9
65

First, understand that those lines are not equivalent.

int* anInt = (int*)aFloat; // is equivalent to

int* anInt = reinterpret_cast<int*>(aFloat); 

What is happening here is that the programmer is asking the compiler to do whatever it can to make the cast.

The difference is important because using static_cast will only ask for a base type that is "safe" to convert to, where reinterpret_cast will convert to anything, possibly by just mapping the wanted memory layout over the memory of the given object.

So, as the "filter" is not the same, using a specific cast is more clear and safe than using the C cast. If you rely on the compiler (or runtime implementation if you use dynamic_cast) to tell you where you did something wrong, by avoid using C cast and reinterepret_cast.

Now that this is more clear, there is another thing: static_cast, reinterpret_cast, const_cast and dynamic_cast are easier to search for.

And the ultimate point: they are ugly. That's wanted. Potentially buggy code, code smells, obvious "tricks" that might generate bugs, are easier to track when it's associated with ugly look. Bad code should be ugly.

That's "by design". And that allows the developer to know where he could have done things better (by totally avoiding casts, if not really needed) and where it's fine but it's "documented" in the code by "marking" it as ugly.

A secondary reason for introducing the new-style cast was that C-style casts are very hard to spot in a program. For example, you can't conveniently search for casts using an ordinary editor or word processor. This near-invisibility of C-style casts is especially unfortunate because they are so potentially damaging. An ugly operation should have an ugly syntactic form. That observation was part of the reason for choosing the syntax for the new-style casts. A further reason was for the new-style casts to match the template notation, so that programmers can write their own casts, especially run-time checked casts.

Maybe, because static_cast is so ugly and so relatively hard to type, you're more likely to think twice before using one? That would be good, because casts really are mostly avoidable in modern C++.

Source: Bjarne Stroustrup (C++ creator)

2 of 9
41

C++ casts are more restrictive (so express your intent better and make code review easier, etc.). They're also much easier to search for, if you ever need to.

🌐
Stack Overflow
stackoverflow.com › questions › tagged › static-cast
Frequent 'static-cast' Questions - Stack Overflow
Say I want to cast A* to char* and vice-versa, we have two choices (I mean, many of us think we've two choices, because both seems to work! Hence the confusion!): struct A { int age; char ... ... See the code below. a) Does, in this case (simple inheritance, no virtual members), the static cast in B::df() have any overhead (whatsoever)?
Top answer
1 of 3
30

It's possible to make that work, but not via overloading static_cast<>(). You do so by overloading the typecast operator:

class Square
{
public:
    Square(int side) : side(side) {}
    operator int() const { return side * side; } // overloaded typecast operator
private:
    int side;
};

// ...

// Compiler calls Square::operator int() to convert aSquare into an int
cout << static_cast<int>(aSquare) <<endl;

Beware that overloaded typecast operators more often than not tend to do more harm than good. They make lots of nonsensical implicit cast operations possible. When you read this code snippet below, do you think "a is going to get the area of s"?

Square aSquare;
int a = aSquare; // What the heck does this do?

I certainly don't. This makes way more sense and is much more readable:

Square aSquare;
int a = aSquare.GetArea();

Not to mention that typically you want to be able to access other information about Square, like GetSide() or GetApothem() or GetPerimeter() or whatever. operator int() obviously can return only one int, and you can't have multiple operator int()s as members of a class.

Here's another situation where the operator int() makes code that compiles yet makes no sense whatsoever:

Square s;
if(s > 42) {} // Huh?!

What does it mean for a Square to be greater than 42? It's nonsense, but with the operator int() the code above will compile as Shape is now convertible to an int which can be compared to another int with a value 4.

So don't write typecast operators like that. In fact if you're overloading typecast operators you may want to think twice about what you're doing. There's actually only a few cases where overloading the typecast operator is useful in modern C++ (e.g. the safe bool idiom).

2 of 3
6

You can overload the cast operator:

struct square {
  operator int() const {
    return (side * side);
  }
  int side;
};

The only problem is that it will be used implicitly, and casting doesn't make much sense here. You also can't distinguish between the different types of casts (static_cast, c-style, etc)

This is the preferred way to do things:

struct square {
  int get_area() const {
    return (side * side);
  }
  int side;
}

If you must use a cast, use C++11 feature and mark it explicit. This prevents implicit casting mistakes.

🌐
Stack Overflow
stackoverflow.com › questions › tagged › static-cast
Highest scored 'static-cast' questions - Stack Overflow
When I try to use a static_cast to cast a double* to an int*, I get the following error: invalid static_cast from type ‘double*’ to type ‘int*’ Here is the code: #include <iostream> int main() ... ... Domain expertise still wanted: the latest trends in AI-assisted knowledge for... ... I’m Jody, the Chief Product and Technology Officer at Stack Overflow.