473,666 Members | 2,713 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

handling overflow, underflow etc

Hi, I have written a small function that can (I think) deal with
overflow/underflow while adding integers and divide by zero problem.
Can some one please tell me if I have done it correctly ? Would it be
safe to extend it to double precision floating point numbers since we
know that there is always some margin for error while adding floating
point numbers ? What other functions should I look to implement for my
project ?

#include <stdio.h>
#include <limits.h>

int add_chk(int a, int b)
{
if (b 0)
{
if (a INT_MAX - b)
{
fprintf(stderr, "Overflow error\n");
return (INT_MAX);
}
}

if (b < 0)
{
if (a < INT_MIN - b)
{
fprintf(stderr, "Underflow error\n");
return (INT_MIN);
}
}

return (a + b);
}

int div_chk(int a, int b)
{
if (b == 0)
{
fprintf(stderr, "Division by zero attempted\n");
return (INT_MAX);
}

return (a/b);
}

int main(void)
{
int i;
int x, y;

clrscr();
printf("Enter two numbers\n");
if (scanf("%d %d", &x, &y) != 2)
{
fprintf(stderr, "Error in user input\n");
return (1);
}

if ((x < INT_MAX && x INT_MIN) && ( y < INT_MAX && y >
INT_MIN))
{
i = add_chk(x, y);
printf("Sum: %d\n", i);
i = div_chk(x, y);
printf("Div: %d\n", i);
}
else
{
fprintf(stderr, "Values entered are out of range\n");
return (1);
}
return (0);
}
Jul 2 '08 #1
11 3184
pereges wrote:
Hi, I have written a small function that can (I think) deal with
overflow/underflow while adding integers and divide by zero problem.
Can some one please tell me if I have done it correctly ? Would it be
safe to extend it to double precision floating point numbers since we
know that there is always some margin for error while adding floating
point numbers ? What other functions should I look to implement for my
project ?
[...]
int div_chk(int a, int b)
{
if (b == 0)
{
fprintf(stderr, "Division by zero attempted\n");
return (INT_MAX);
I'm not convinced INT_MAX is the best value to return for
-1/0 or for 0/0.
}

return (a/b);
INT_MIN/-1 is likely to make trouble, or at least raise
a few eyebrows. Your test program (for reasons unclear to me)
prevents this case from arising, but if you're trying to write
a general-purpose library you should probably not rely on the
inputs being "sanitized. "

As to whether all this is a good idea -- well, I think you
need to consider the "use cases" for your library: What kinds
of programs will use it, and why, and what behavior would the
programs expect? To put it another way, I fear you may already
be making tactical decisions without first settling on strategy.

--
Er*********@sun .com
Jul 2 '08 #2
pereges wrote:
#include <stdio.h>
#include <limits.h>

int add_chk(int a, int b)
{
if (b 0)
{
if (a INT_MAX - b)
{
fprintf(stderr, "Overflow error\n");
return (INT_MAX);
}
}

if (b < 0)
I'd use else if.
{
if (a < INT_MIN - b)
{
fprintf(stderr, "Underflow error\n");
This is not normally thought of as underflow. Underflow is a lack of
precision in floating point, e.g. 10e50 + 10e-50 typically underflows.
return (INT_MIN);
}
}

return (a + b);
}
Printing to stderr couples your function. That's not necessarily
bad, but I prefer to set errno to ERANGE and return 0. Let the
caller decide what to with the overflow.

....
int main(void)
{
int i;
int x, y;

clrscr();
Please elide non-standard functions when you post to clc.
printf("Enter two numbers\n");
if (scanf("%d %d", &x, &y) != 2)
{
fprintf(stderr, "Error in user input\n");
return (1);
Please use portable return values.
}

if ((x < INT_MAX && x INT_MIN) && ( y < INT_MAX && y >
INT_MIN))
Since x and y are ints, at what point in time will their values be
outside the range of an int?
{
i = add_chk(x, y);
printf("Sum: %d\n", i);
i = div_chk(x, y);
printf("Div: %d\n", i);
}
else
{
fprintf(stderr, "Values entered are out of range\n");
return (1);
}
return (0);
}
--
Peter
Jul 2 '08 #3

"Peter Nilsson" <ai***@acay.com .auha scritto nel messaggio
news:31******** *************** ***********@v26 g2000prm.google groups.com...
pereges wrote:
> printf("Enter two numbers\n");
if (scanf("%d %d", &x, &y) != 2)
{
fprintf(stderr, "Error in user input\n");
return (1);

Please use portable return values.
Just out of curiosity, do you know a system which has these macros defined
with different values?

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

I understand that only 0 and EXIT_SUCCESS, EXIT_FAILURE are defined by the
C standard but wondered if that restriction was purely philosophical.. ..

Jul 4 '08 #4
Lorenzo Villari wrote:
"Peter Nilsson" <ai***@acay.com .auha scritto nel messaggio
news:31******** *************** ***********@v26 g2000prm.google groups.com...
>pereges wrote:
>> printf("Enter two numbers\n");
if (scanf("%d %d", &x, &y) != 2)
{
fprintf(stderr, "Error in user input\n");
return (1);
Please use portable return values.

Just out of curiosity, do you know a system which has these macros defined
with different values?

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

I understand that only 0 and EXIT_SUCCESS, EXIT_FAILURE are defined by the
C standard but wondered if that restriction was purely philosophical.. ..
OpenVMS. (But it's been more than fifteen years since
I used it, and things may have changed.)

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jul 4 '08 #5
Eric Sosman wrote:
Lorenzo Villari wrote:
>"Peter Nilsson" <ai***@acay.com .auha scritto nel messaggio
news:31******* *************** ************@v2 6g2000prm.googl egroups.com...
>>pereges wrote:
printf("Enter two numbers\n");
if (scanf("%d %d", &x, &y) != 2)
{
fprintf(stderr, "Error in user input\n");
return (1);
Please use portable return values.

Just out of curiosity, do you know a system which has these macros
defined
with different values?

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

I understand that only 0 and EXIT_SUCCESS, EXIT_FAILURE are defined
by the
C standard but wondered if that restriction was purely philosophical.. ..
Do not confuse pedantry with philosophy.
>
OpenVMS. (But it's been more than fifteen years since
I used it, and things may have changed.)
Yeah... Most of the regulars answer stuff like this when they
are asked for a concrete example.
--
jacob navia
jacob at jacob point remcomp point fr
logiciels/informatique
http://www.cs.virginia.edu/~lcc-win32
Jul 4 '08 #6
Lorenzo Villari wrote:
>
.... snip ...
>
Just out of curiosity, do you know a system which has these macros
defined with different values?

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

I understand that only 0 and EXIT_SUCCESS, EXIT_FAILURE are
defined by the C standard but wondered if that restriction was
purely philosophical.. ..
Yes. No.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Jul 4 '08 #7
jacob navia wrote:
Eric Sosman wrote:
>Lorenzo Villari wrote:
>>"Peter Nilsson" <ai***@acay.com .auha scritto nel messaggio
news:31******** *************** ***********@v26 g2000prm.google groups.com...
>>>pereges wrote:
printf("Enter two numbers\n");
if (scanf("%d %d", &x, &y) != 2)
{
fprintf(stderr, "Error in user input\n");
return (1);
Please use portable return values.

Just out of curiosity, do you know a system which has these macros
defined
with different values?

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

I understand that only 0 and EXIT_SUCCESS, EXIT_FAILURE are defined
by the
C standard but wondered if that restriction was purely
philosophical ....

Do not confuse pedantry with philosophy.
>>
OpenVMS. (But it's been more than fifteen years since
I used it, and things may have changed.)

Yeah... Most of the regulars answer stuff like this when they
are asked for a concrete example.
EXIT_FAILURE is perfectly appropriate to indicate generic failure. I
would consider other values only when I need to return more than just
success or failure. This is not necessary in small programs of the like
that are most often posted here in c.l.c.

Gratuitously using 1 when EXIT_FAILURE will do is merely restricting
portability for no good reason.

Jul 4 '08 #8
In C99 it seems there are some very good methods to handle such math
errors. My pelles C compiler lists a few of them but then again
portability is the problem.
Jul 4 '08 #9
pereges wrote:
In C99 it seems there are some very good methods to handle such math
errors.
Such as?
My pelles C compiler lists a few of them but then again
portability is the problem.
How many systems do you need your program to work under? Have you
checked whether they have C99 conformant implementations or compiler
that implement the subset of C99 that interests you?

Jul 4 '08 #10

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

Similar topics

0
1926
by: Viktor Lundström | last post by:
Hi! I recently decided to write a streambuf which handles streamed IO to a device (ie. a socket). Now, in an effort to move away from C-style IO error handling (ie. if(read(..) == -1) ...), I decided to make my streambuf raise exceptions upon device error states. The code is supposed to run on several platforms, but there seems to be some inconsistency between the different iostream implementations. This led me to believe that I'm...
7
8492
by: Oplec | last post by:
Hello, How can underflow and overflow of the basic arithmetic types be tested for using standard C++? For instance, if two long doubles are multiplied together, test whether or not the result is too large to fit in a long double? Thank you for your time, Oplec.
4
3549
by: aling | last post by:
Given: signed a, b; How to judge overflow of the sum of these two operands? Just use one *if* statement. Is this statement right? if ((a>0 && b>0 && sum<=0) || (a<0 && b<0 && sum>=0)) // overflow else // not overflow
5
2565
by: juergen perlinger | last post by:
Hello out there. sometimes I need to have proper control of the floating point arithmetic of the C(and C++) runtime system, and using the f.p. exception handling of the C99 standard is quite handy for that purpose. The only problem when dealing with f.p. exception signals is that there is (afaik) no specification *when* the f.p. exception is raised, with one notable exception: 'feraiseexcept(int)' raises the exceptions passed in the...
2
6063
by: Paul Emmons | last post by:
Can anyone suggest example code, or how to proceed, in adding or subtracting two long long integers (I'm working in gcc with Linux, where a long long is 64 bits) and determining whether an overflow or underflow occurs, invalidating the result? I have written a solution in assembler. It's simple, thanks to the overflow flag. But without access to this part of the hardware in the C language, how would one do it? Thank you for your...
5
9220
by: Ian Pilcher | last post by:
I'm trying to figure out if an increment to a variable of an integer type, followed by a decrement, (or vice versa) is guaranteed to restore the variable to its initial value, even if the first operation causes the variable to overflow/underflow. In other words, if foo_t is an integer type, are the following two functions guaranteed to *always* return a non-zero value? int check_overflow(foo_t f) {
4
4138
by: Tom | last post by:
I have a VB.NET framework 1.1 application that I am installing on my user's workstation. It works fine on EVERY machine except for one - on this one machine it generates a 'Overflow or underflow in the arithmetic operation' when I attempt to instantiate my first form, as so: Dim frm As New frmMyForm() Based on some things I saw here, I thought it might be that this workstation didn't have a MS Sans Seriff font on it (since that is the...
4
9943
by: Raymond | last post by:
Source: http://moryton.blogspot.com/2007/08/detecting-overflowunderflow-when.html Example from source: char unsigned augend (255); char unsigned const addend (255); char unsigned const sum (augend + addend); if (sum < augend)
2
3083
by: jou00jou | last post by:
Hi, I have trouble using sscanf and fgets to check for overflow. I will post the assignment specification so I could help whoever would kindly like to offer his/her help. ____________________________________________________________________________________ 1) The program should expect 2 decimal integers per line. Let's call these n1 and n2. 2) For each such input line it should output the value of n1 + 2 * n2 (followed by a newline...
0
8438
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
8348
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8863
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
7376
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...
0
5660
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
4186
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
4356
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2765
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
2
1761
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.