Why in C++ do we use DWORD rather than unsigned int? [duplicate] Ask Question

Why in C++ do we use DWORD rather than unsigned int? [duplicate] Ask Question

I'm not afraid to admit that I'm somewhat of a C++ newbie, so this might seem like a silly question but....

I see DWORD used all over the place in code examples. When I look up what a DWORD truly means, its apparently just an unsigned int (0 to 4,294,967,295). So my question then is, why do we have DWORD? What does it give us that the integral type 'unsigned int' does not? Does it have something to do with portability and machine differences?

ベストアンサー1

DWORD is not a C++ type, it's defined in <windows.h>.

The reason is that DWORD has a specific range and format Windows functions rely on, so if you require that specific range use that type. (Or as they say "When in Rome, do as the Romans do.") For you, that happens to correspond to unsigned int, but that might not always be the case. To be safe, use DWORD when a DWORD is expected, regardless of what it may actually be.

For example, if they ever changed the range or format of unsigned int they could use a different type to underly DWORD to keep the same requirements, and all code using DWORD would be none-the-wiser. (Likewise, they could decide DWORD needs to be unsigned long long, change it, and all code using DWORD would be none-the-wiser.)


Also note unsigned int does not necessary have the range 0 to 4,294,967,295. See here.

おすすめ記事