Solved

Testing for USHORT variable overflow

Posted on 2002-03-29
3
608 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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 tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

705 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now