No-overflow cast on x64

Posted by Cheeso on Stack Overflow See other posts from Stack Overflow or by Cheeso
Published on 2010-05-29T21:02:38Z Indexed on 2010/05/29 21:12 UTC
Read the original article Hit count: 262

Filed under:
|
|
|
|

I have an existing C codebase that works on x86.

I'm now compiling it for x64.

What I'd like to do is cast a size_t to a DWORD, and throw an exception if there's a loss of data.

Q: Is there an idiom for this?


Here's why I'm doing this:

A bunch of Windows APIs accept DWORDs as arguments, and the code currently assumes sizeof(DWORD)==sizeof(size_t). That assumption holds for x86, but not for x64. So when compiling for x64, passing size_t in place of a DWORD argument, generates a compile-time warning.

In virtually all of these cases the actual size is not going to exceed 2^32. But I want to code it defensively and explicitly.

This is my first x64 project, so... be gentle.

© Stack Overflow or respective owner

Related posts about Windows

Related posts about visual-c++