Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 618
  • Last Modified:

Testing for USHORT variable overflow

As part of a bit of defensive programming, I would like to use an assert to make sure that when I cast a ULONG into a USHORT variable that I won't be overflowing the size of numbers that a USHORT can handle.  Will the following work, do you think?  I think it needs the cast to ULONG so that the comparison is done as a ULONG.

#define MAX_USHORT    ((ULONG) ~((USHORT) 0x0))

ASSERT(myushortvar <= MAX_USHORT);
0
ckurt99
Asked:
ckurt99
1 Solution
 
BlackDiamondCommented:
The cast would be implied, but it is still a good idea to leave it there (you can never be too careful).  Otherwise, your assertion looks fine.

A recommendation that I would make is that you try to define the cases where this assertion would fail, and add some real error handling instead of just doing an assert and dying.  Only use assert if there is no way to determine why your value would be outside your scope, or the value is being provided by an external source that you have no control over (or there is no way to remedy the value from this point in your code).  I would still advocate real error handling though.
0
 
ozoCommented:
If myushortvar is USHORT the ASSERT will always be true
0
 
ckurt99Author Commented:
Thank you for pointing that out, ozo. I should have used result_of_ulong_calc instead of myushortvar.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now