Solved

Testing for USHORT variable overflow

Posted on 2002-03-29
3
614 Views
Last Modified: 2010-05-18
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
Comment
Question by:ckurt99
3 Comments
 
LVL 5

Accepted Solution

by:
BlackDiamond earned 50 total points
ID: 6905596
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
 
LVL 84

Expert Comment

by:ozo
ID: 6905609
If myushortvar is USHORT the ASSERT will always be true
0
 
LVL 3

Author Comment

by:ckurt99
ID: 6905613
Thank you for pointing that out, ozo. I should have used result_of_ulong_calc instead of myushortvar.
0

Featured Post

Industry Leaders: 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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question