Here are two very similar snippets:
vector<int> a;
int n = static_cast<int>(a.size());
// ---------
int f(const vector<int>& a) {
return static_cast<int>(a.size());
}
Here I explicitly cast a value of type size_t
to type int
. If I omit static_cast
then the same cast applies implicitly.
Of which kind would this implicit cast be? Is it safe to omit static_cast
in explicit assignments and return statements?
This cast is not that safe, actualy the value of
n
may be implementation defined (c++ standard [conv.integral]):If you enable all warning, and don't use the static_cast, your compiler may inform you about a narrowing conversion. If you use the
static_cast
, you inform reader of your code that you know for sure thata.size() <= std::numeric_limits<int>::max()
or that you know what your implementation is going to do if such a condition does not hold.(notice that it could be possible that previous comparison also invokes implementation defined conversion if std::size_t is smaller than int, the c++ standard allowes it)