2

Recently, I am confused with this two expression - (type)value and type(value).

For example : size_t c = size_t(-1); size_t c = (size_t)-1;

what is the difference?

alk
  • 69,737
  • 10
  • 105
  • 255

2 Answers2

5

The former is C++, it's doing direct initialization by calling a constructor.

The second is C (or C++), it's doing a cast.

So, there's a lot of difference from a C programmer's point of view.

Also, this is a pretty bad idea, since size_t is an unsigned type. This should be done using ssize_t, which is signed and removes the need for the cast.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
  • 1
    -1 "it's doing direct initialization"; no it's not, that's still a copy initialization. a direct initialization is e.g. `size_t x(-1)`. also, `ssize_t` is not a standard C or C++ type, it's a Posix type. On 32-bit systems and higher the signed type corresponding to `size_t` is (in practice) `ptrdiff_t`. And anyway that's the type to recommend for the purpose where you recommend the Posix-specific type. Third, both are casts, and the effect of the C++ notation cast is defined as equivalent to the C notation cast. – Cheers and hth. - Alf Jan 24 '13 at 16:08
2

In C, only one of these is a valid expression.

In C++, they are exactly the same, they are two alternative forms of writing an explicit cast expression: C-style and the functional style.

Community
  • 1
  • 1
Cubbi
  • 46,567
  • 13
  • 103
  • 169