Chris Jefferson
Chris Jefferson

Reputation: 7157

Undefined behavior when exceed 64 bits

In my current 32-bit application, I check (very occasionally) for overflow by doing operations on 64-bit integers.

However, on 64-bit systems there does not seem to be a standard 128-bit integer. Is there a simple way of checking for overflow, or a way of getting 128-bit integers, which works on all OSes and compilers?

I tried using GMP as a more generic solution, but it is a little heavyweight for my requirements.

Efficiency is not too important, no processor specific-ASM is.

Upvotes: 1

Views: 1419

Answers (3)

paxdiablo
paxdiablo

Reputation: 881463

One solution would be to create a class around the 64-bit int which overrode the arithmetic operators to check before performing the operation.

I can't remember the operatorX syntax off the top of my head (I switched from C++ to Java a long time ago) but a sample would be:

int64 myint64::add (int64 a, int64 b) {
    if (MAX_INT64 - a > b) {
        // error condition here.
    }
    return a + b;
}
int64 myint64::mul (int64 a, int64 b) {
    if (MAX_INT64 / a > b) {
        // error condition here.
    }
    return a * b;
}

Similar for any other arithmetic operation, although this could get very complicated for non-basic functions such as powers, factorials and such.

However, if you build those from the basic arithmetic building blocks, they'll work.

Upvotes: 1

Michael Burr
Michael Burr

Reputation: 340208

Much of the discussion in this question applies:

How to detect integer overflow?

Many of the techniques used for 32-bit overflow chacking apply to 64-bits as well (not all of the techniques discussed use the next larger integer type to handle the overflow).

Upvotes: 3

Draemon
Draemon

Reputation: 34711

this document talks about catching overflows (in c) in detail. I don't know if there are better ways of doing this in C++.

Upvotes: 2

Related Questions