Solved

Testing for USHORT variable overflow

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

786 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