473,769 Members | 5,877 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

hhow to detect overflow in integer calculation

Hi,
If I have many integer calculation in my code, what's the best way to
detect integer overflow?

unsigned int i1 = 0xFFFFFF00, i2 = 0xFFFF;

then in statement unsigned int i3 = i1 + i2; there is overflow and
the result is not what I want. If such sum calculation scatters around
my code, I wonder what's the best way to catch it?

Thanks.
Jul 22 '05 #1
1 4342

"John Black" <bl***@eed.co m> wrote in message
news:40******** *******@eed.com ...
Hi,
If I have many integer calculation in my code, what's the best way to
detect integer overflow?

unsigned int i1 = 0xFFFFFF00, i2 = 0xFFFF;

then in statement unsigned int i3 = i1 + i2; there is overflow and
the result is not what I want. If such sum calculation scatters around
my code, I wonder what's the best way to catch it?


how about

if (std::numeric_l imits<unsigned int>::max() - i1 < i2)
cout << "overflow";

#include <limits> to get std::numeric_li mits.

And of course put all this in a function, or better still define a class
which overloads all the arithmetic operators and does the overflow checking
for you.

class SafeUInt
{
public:
SafeUInt(unsign ed int v) : val(v) {}
...
private:
unsigned int val;
};

SafeUInt operator+(const SafeUInt& x, const SafeUInt& y)
{
// overflow detection here
...
}

john
Jul 22 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
17807
by: Vivek Mohan | last post by:
Hi, I am using gcc, and I am a bit confused about the warning message I got when I compiled and ran this small code snippet - int main() { unsigned long x = 3*1024*1024*1024; /* 3GB */ printf(" %x ", x); } I got the following error,
27
4566
by: REH | last post by:
I asked this on c.l.c++, but they suggested you folks may be better able to answer. Basically, I am trying to write code to detect overflows in signed integer math. I am trying to make it as efficient as possible without resorting to assembly language, and without causing undefined behavior. That, of course, means catching the overflow before it happens. What I asked was (stripping any relevance to C++):
25
6263
by: junky_fellow | last post by:
Is there any way by which the overflow during addition of two integers may be detected ? eg. suppose we have three unsigned integers, a ,b, c. we are doing a check like if ((a +b) > c) do something;
3
4587
by: linq936 | last post by:
I have some algorithm dealing with unsigned int calculation a lot, I am trying to add some check for overflow. The initial thinking was very easy, just do something like this, int addition(unsigned int i1, unsigned int i2) { if ( i1 + i2 < i1 || i1 + i2 < i2 ) { ...throw some expception... } return i1+i2; }
3
44741
by: SheldonMopes | last post by:
I sometimes get a pop-up box that reads "Overflow" and the module that is executing pauses. It doesn't get caught by my error trapping, and it seems to be randow. By random, I mean usually in the same section of code, but I can run the code a few times, then it appears. I can't reproduce it when I want to, and I have no idea what is causing it. Any ideas ? Thanks By the way the code is some record manipulation of 2 recordsets.
7
4855
by: AmazingAccuracy.com | last post by:
I'm puzzled. The following code is designed to take a date and a weekday count value, and return the future date. For example, if I supply it a starting date of 4/25/2007 and a count of 37, it should return a date that is 37 weekdays only from 4/25/2007. It should not count any weekends, only Monday-Friday days. When I ran this code, it came back with an OVERFLOW error. Huh?
7
54264
by: LucasLondon | last post by:
Hi, I have the code below that I adapted to loop through each column of data (Columns A to GR) to perform an a calculation based on the data in rows 2 to 31 of each column and place the calculated statistic in row 35 for each column of data. The problem is the code runs fine for the first six columns of data (i.e row 35 for columns A:F get populated with a correctly calculated statistic but code stops running at column G, and generates a...
17
7564
by: Tarique | last post by:
This program was compiled on MS Visual C++ 08 /*Fibonacci Numbers*/ #include<stdio.h> #include<limits.h> void fibonacci(int n) { unsigned long long fib0 = 0; /*First Fibonacci Number*/
42
7034
by: thomas.mertes | last post by:
Is it possible to use some C or compiler extension to catch integer overflow? The situation is as follows: I use C as target language for compiled Seed7 programs. For integer computions the C type 'long' is used. That way native C speed can be reached. Now I want to experiment with raising a Seed7 exception (which is emulated with setjmp(), longjmp() in C) for integer
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10222
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9866
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8876
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3967
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.