3

From this answer to the question "When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?":

C-style cast and function-style cast are casts using (type)object or type(object), respectively.

It then begins to list the behavior of the C-style cast, but never tells whether the function-style cast is identical or not.

I'm asking because Resharper for C++ warns me in case of C-style casts but does not warn me in case of function-style casts:

Resharper screenshot

In what way is the the function-style case different from the C-style cast? Or, if they are identical, is it a bug in Resharper and it should emit a warning, too? Is int(d) safe to use? It looks much simpler than the suggested static_cast<int>(d);.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • Note that the two casts of `d` are rather different statements. One is an initialisation, the other an assignment. You should really compare `int i = int(d); int j = (int)d;` or `int i; i = int(d); i = (int)d;` – Caleth Oct 22 '18 at 13:44
  • @Caleth: wouldn't the compiler optimize both ways into the same result? – Thomas Weller Oct 22 '18 at 14:41
  • In the case of `int`s? yes. In general? no. But my point is that there are *different language rules* about declarations and assignments. – Caleth Oct 22 '18 at 14:49

1 Answers1

5

I don't have a quote from the standard, but cppreference is usually good enough.

Explicit type conversion

The functional cast expression consists of a simple type specifier or a typedef specifier (in other words, a single-word type name: unsigned int(expression) or int*(expression) are not valid), followed by a single expression in parentheses. This cast expression is exactly equivalent to the corresponding C-style cast expression.

As for Resharper, it's possible that to it C++ cast includes a functional cast, as that is only valid in C++.

The answer you linked in your question explains how safe a functional cast is. In your case int(d) should be equivalent to static_cast<int>(d). But in general a C-style or functional cast are unsafe as they can be equivalent to reinterpret_cast in certain situations, e.g. (double*)some_int_ptr.

Kevin
  • 6,993
  • 1
  • 15
  • 24
  • "no cast is required anyway"? If I don't use a cast, the compiler emits warning C4244 – Thomas Weller Oct 22 '18 at 07:24
  • Apologies. With the compiler I use (gcc) you have to explicitly ask for it to warn about this (`-Wconversion` for those interested). Update my answer. – Kevin Oct 22 '18 at 13:29