Thread: Checking if long int overflowed

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    6

    Checking if long int overflowed

    Hi.

    I dont know how to efficiently check if a given type range has been surpassed, e.g.

    int (32 bit)
    range 0 - 4294967295

    having:
    int number =4294967293

    int sum = number + 4355435;

    and now sum overflowed...

    Please help.

  2. #2
    Registered User
    Join Date
    Mar 2005
    Posts
    38
    Unsigned int (32 bit) has range [0, 4294967296]. But if defined as you do, it's signed: range [-2147483648, 2147483647]. You should either do extra work yourself to ascertain overflow doesn't occur, or use a more suitable datatype (like 64 bits long long).

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    #include <stdio.h>
    #include <limits.h>
    
    int main(void)
    {
       long a = LONG_MAX - 2, b = 5;
       if ( b > LONG_MAX - a )
       {
          puts("overflow will occur for a + b");
       }
       return 0;
    }
    
    /* my output
    overflow will occur for a + b
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Drawing Program
    By Max_Payne in forum C++ Programming
    Replies: 21
    Last Post: 12-21-2007, 05:34 PM
  2. Moving Average Question
    By GCNDoug in forum C Programming
    Replies: 4
    Last Post: 04-23-2007, 11:05 PM
  3. Need help understanding info in a header file
    By hicpics in forum C Programming
    Replies: 8
    Last Post: 12-02-2005, 12:36 PM
  4. problem with sorting
    By pinkpenguin in forum C Programming
    Replies: 2
    Last Post: 11-18-2005, 11:06 AM
  5. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM