2

Common advice when writing C++ states that implicit conversions should be avoided in favour of explicit casts.

int x = myUnsignedLongVar; // should be avoided

while

int x = static_cast<int>(myUnsignedLongVar); // is preferred

Does a static_cast make this conversion any safer? As far as I'm aware both conversions are implementation defined? Is the static_cast just a signal to indicate more verbosely that this operation is potentially implementation defined?

And who's implementation? Is the operation dependent on the implementation of the compiler or the CPU?

iwans
  • 445
  • 3
  • 13
  • 3
    There is no such thing as implicit cast. A cast is an explicit type conversion. A cast is not safer than an implicit conversion. Its advantage is that it is explicit, i.e. the human behind the keyboard sees what is happening. – n. m. could be an AI Jun 21 '21 at 08:37
  • I've re-worded to remove implicit cast – iwans Jun 21 '21 at 08:38

2 Answers2

1

Both examples would produce the same code.
But, in the second one everyone knows that there’s a cast to int.
In the first one could assume myUnsignedLongVar is int.
In order to make sure nobody misses the cast, guidelines and compilers recommend making it explicit.

Daniel
  • 30,896
  • 18
  • 85
  • 139
1

I believe your example is somewhat narrow to show the real difference between different types of casting. If you are simply casting from unsigned int to int, or from double to int, this may not show its real value.

The real value comes when you do not want to allow casting to cause bugs in your program. For example when performing comparisons between signed and unsigned types, or pointer or changing object types. Moreover, C++ style casting i.e. static cast is checked by the compiler. Another benefit is what you already mentioned. Verbosity. They ensure that the authors intent is captured.

Several answers to this question contain a nice summary and comparison between different types of casting.

Keivan
  • 673
  • 7
  • 15