Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reinterpret an unsigned long (DWORD) as a signed long in C++?

I want to reinterpret an unsigned long (actually, a DWORD) as a signed long. I tried:

DWORD x;
long y = reinterpret_cast<signed long>(x);

However, VC++2010 intellisense tells me "Invalid type conversion". Why? How do I fix it?

like image 257
Felix Dombek Avatar asked Jul 15 '11 15:07

Felix Dombek


2 Answers

You don't need reinterpret_cast to convert unsigned type into a signed one, static_cast will do.

like image 107
Cat Plus Plus Avatar answered Sep 22 '22 09:09

Cat Plus Plus


try static_cast instead. VC generates an error if you try an excessively permissive cast (like using reinterpret_cast when static_cast or const_cast will suffice).

There are 5 types of casts in C++, each of which allows you to do more (grants more permissions). The least permissive casts are const casts (const_cast<int>(<const int>)) which allow you to change the const modifier. There are static casts (static_cast<int>)(<short>)) which allow you to perform type safe coersions (cast base to derived, for example).There are dynamic casts (dynamic_cast<derived_type>(base_type) that allow you to cast from one type to another if there is a legal conversion between the two (and that return null if there is no conversion). Finally, there are casts that allow conversion between unrelated types - reinterpret_cast reinterpret_cast<int>(<void *>) and C style cast (int)<void *>.

I don't have a good way of describing these different types of casts, so I describe them as "more permissive" because each of them allows you to do more.

VC warns you if you are using a reinterpret cast when one of the other cast types would be more appropriate to achieve your goal. C style casts don't have a similar warning for backwards compatibility.

like image 29
ReinstateMonica Larry Osterman Avatar answered Sep 18 '22 09:09

ReinstateMonica Larry Osterman