Topic: Overflow, underflow, and exceptions
Author: Scott Meyers <smeyers@aristeia.com>
Date: 1999/01/14 Raw View
Is an implementation allowed to throw an exception in the case of underflow
or overflow of built-in types? Chapter 5 paragraph 5 suggests yes:
If during the evaluation of an expression, the result is not mathemat-
ically defined or not in the range of representable values for its
type, the behavior is undefined, unless such an expression is a con-
stant expression (_expr.const_), in which case the program is ill-
formed. [Note: most existing implementations of C++ ignore integer
overflows. Treatment of division by zero, forming a remainder using a
zero divisor, and all floating point exceptions vary among machines,
and is usually adjustable by a library function. ]
Hence,
int i = std::numeric_limits<int>::max(); // set i to the maximum int value
i++; // results are undefined, hence an implementation could choose
// to throw an exception
If my understanding is correct, what is the situation in C? Is the
behavior of the following also undefined in C?
int i = INT_MAX;
i++;
Thanks,
Scott
Scott Meyers, Ph.D. Voice: 503/638-6028
Author: Effective C++ CD Fax: 503/638-6614
Effective C++ Email: smeyers@aristeia.com
More Effective C++ WWW: http://www.aristeia.com/
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]
Author: Bill Seymour <bsey@pobox.com>
Date: 1999/01/14 Raw View
Scott Meyers wrote:
>
> Is the behavior of the following also undefined in C?
>
> int i = INT_MAX;
> i++;
>
Yes, for signed arithmetic, overflow is undefined and so
implementations are permitted to trap. This is not the
case with unsigned arithmetic which never overflows,
but rather just wraps around modulo Umumble_MAX + 1.
I assume that this behavior was inherited by C++.
--Bill Seymour
Programmer/Analyst, U.S. Postal Service
mailto:wseymour@email.usps.gov
Vocabulary Representative, J11 - Editor, C9X Rationale -
Member, U.S. Delegation to SC22 WG14
mailto:bsey@pobox.com
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]