SlideShare a Scribd company logo
1 of 1
Download to read offline
The Joy of Programming  |                             Guest Column 


                                                                                                              S.G. Ganesh



How to Detect Integer Overflow
Integer overflows often result in nasty bugs. In this column, we’ll look at some techniques to detect an 
overflow before it occurs.



I
    nteger overflow happens because computers use fixed                   if ( ((i + j) >  INT_MAX) || ((i + j) < INT_MIN) )
    width to represent integers. So which are the operations                   return 0; // wrong implementation
    that result in overflow? Bitwise and logical operations
cannot overflow, while cast and arithmetic operations can.                    Why? Because (i + j) overflows, and when its result is
For example, ++ and += operators can overflow, whereas &&                 stored, it can never be greater than INT_MAX or less than
or & operators (or even << and >> operators) cannot.                      INT_MIN! That’s precisely the condition (overflow) we
     Regarding arithmetic operators, it is obvious that operations        want to detect, so it won’t work.
like addition, subtraction and multiplication can overflow.                   How about modifying the checking expression? Instead
     How about operations like (unary) negation, division                 of ((i + j) > INT_MAX), we can check the condition (i >
and mod (remainder)? For unary negation, -MIN_INT is                      INT_MAX - j) by moving j to the RHS of the expression. So,
equal to MIN_INT (and not MAX_INT), so it overflows.                      the condition in isSafeToAdd can be rewritten as:
Following the same logic, division overflows for the
expression (MIN_INT / -1). How about a mod operation? It                  if( (i > INT_MAX - j) || (i < INT_MIN - j) )
does not overflow. The only possible overflow case (MIN_                         return 0;
INT % -1) is equal to 0 (verify this yourself—the formula for
% operator is “a % b = a - ((a / b) * b)”).                                   That works! But can we simplify it further? From
     Let us focus on addition. For the statement “int k = (i + j);”:      condition (2), we know that for an overflow to occur,
(1) If i and j are of different signs, it cannot overflow.                the signs of i and j should be different. If you notice the
(2) If i and j are of same signs (- or +), it can overflow.               conditions in (3) and (4), the sign bit of the result (k) is
(3) If i and j are positive integers, then their sign bit is zero. If k   different from (i and j). Does this strike you as the check
     is negative, it means its sign bit is 1—it indicates the value       that the ^ operator can be used? How about this check:
     of (i + j) is too large to represent in k, so it overflows.
(4) If i and j are negative integers, then their sign bit is one. If      int k = (i + j); 
     k is positive, it means its sign bit is 0—it indicates that the      if( ((i ^ k) & (j ^ k)) < 0)
     value of (i + j) is too small to represent in k, so it overflows.        return 0;
     To check for overflow, we have to provide checks
for conditions (3) and (4). Here is the straightforward                       Let us check it. Assume that i and j are positive
conversion of these two statements into code. The function                values and when it overflows, the result k will be
isSafeToAdd returns true or false after checking for overflow.            negative. Now the condition (i ^ k) will be a negative
                                                                          value—the sign bit of i is 0 and the sign bit of k is 1; so
 /* Is it safe to add i and j without overflow?                           ^ of the sign bit will be 1 and hence the value of the
Return value 1 indicates there is no overflow;                            expression (i ^ k) is negative. So is the case for (j ^ k)
else it is overflow and not safe to add i and j */                        and when the & of two values is negative; hence, the
int isSafeToAdd(int i, int j) {                                           condition check with < 0 becomes true when there is
   if( (i < 0 && j < 0) && k >=0) ||                                      overflow. When i and j are negative and k is positive,
       (i > 0 && j > 0) && k <=0) )                                       the condition again is < 0 ( following the same logic
       return 0;                                                          described above).
   return 1; // no overflow - safe to add i and j                             So, yes, this also works! Though the if condition is not
}                                                                         very easy to understand, it is correct and is also an efficient
                                                                          solution!
   Well, this does the work, but is inefficient. Can it be
improved? Let us go back and see what i + j is, when it                      About the author:
overflows.                                                                  S G Ganesh is a research engineer in Siemens (Corporate
                                                                            Technology). His latest book is “60 Tips on Object Oriented
   If ((i + j) > INT_MAX) or if ((i + j) < INT_MIN), it
                                                                            Programming”, published by Tata McGraw-Hill. You can reach
overflows. But if we translate this condition directly into                 him at sgganesh@gmail.com.
code, it will not work:

12  |  March 2009 | LINUX For YoU | www.openITis.com

More Related Content

Viewers also liked

8.Integer Overflows
8.Integer Overflows8.Integer Overflows
8.Integer Overflows
phanleson
 
118015425 pengertian-filsafat-objek-material-dan-formal-filsafat
118015425 pengertian-filsafat-objek-material-dan-formal-filsafat118015425 pengertian-filsafat-objek-material-dan-formal-filsafat
118015425 pengertian-filsafat-objek-material-dan-formal-filsafat
Operator Warnet Vast Raha
 
Buffer Overflows
Buffer OverflowsBuffer Overflows
Buffer Overflows
Sumit Kumar
 

Viewers also liked (20)

Grokking Signed Overflows
Grokking Signed OverflowsGrokking Signed Overflows
Grokking Signed Overflows
 
Twist and write
Twist and writeTwist and write
Twist and write
 
8.Integer Overflows
8.Integer Overflows8.Integer Overflows
8.Integer Overflows
 
Jan 2008 Allup
Jan 2008 AllupJan 2008 Allup
Jan 2008 Allup
 
Harnessing Stack Overflow for the IDE - RSSE 2012
Harnessing Stack Overflow for the IDE - RSSE 2012Harnessing Stack Overflow for the IDE - RSSE 2012
Harnessing Stack Overflow for the IDE - RSSE 2012
 
JavaSecure
JavaSecureJavaSecure
JavaSecure
 
Hay necesidad de Comprar un camión?¿
Hay necesidad de Comprar un camión?¿Hay necesidad de Comprar un camión?¿
Hay necesidad de Comprar un camión?¿
 
System Hacking Tutorial #1 - Introduction to Vulnerability and Type of Vulner...
System Hacking Tutorial #1 - Introduction to Vulnerability and Type of Vulner...System Hacking Tutorial #1 - Introduction to Vulnerability and Type of Vulner...
System Hacking Tutorial #1 - Introduction to Vulnerability and Type of Vulner...
 
When good code goes bad
When good code goes badWhen good code goes bad
When good code goes bad
 
Too Long; Didn’t Watch! Extracting Relevant Fragments from Software Developme...
Too Long; Didn’t Watch! Extracting Relevant Fragments from Software Developme...Too Long; Didn’t Watch! Extracting Relevant Fragments from Software Developme...
Too Long; Didn’t Watch! Extracting Relevant Fragments from Software Developme...
 
Exploiting 101
Exploiting 101Exploiting 101
Exploiting 101
 
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
 
Media Files : Android's New Nightmare
Media Files :  Android's New NightmareMedia Files :  Android's New Nightmare
Media Files : Android's New Nightmare
 
118015425 pengertian-filsafat-objek-material-dan-formal-filsafat
118015425 pengertian-filsafat-objek-material-dan-formal-filsafat118015425 pengertian-filsafat-objek-material-dan-formal-filsafat
118015425 pengertian-filsafat-objek-material-dan-formal-filsafat
 
Hta t19
Hta t19Hta t19
Hta t19
 
Microsoft GDI+ JPEG Integer Underflow Vulnerability
Microsoft GDI+ JPEG Integer Underflow VulnerabilityMicrosoft GDI+ JPEG Integer Underflow Vulnerability
Microsoft GDI+ JPEG Integer Underflow Vulnerability
 
Software Security
Software SecuritySoftware Security
Software Security
 
Buffer Overflows
Buffer OverflowsBuffer Overflows
Buffer Overflows
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Chapter 1 computer abstractions and technology
Chapter 1 computer abstractions and technologyChapter 1 computer abstractions and technology
Chapter 1 computer abstractions and technology
 

Similar to 27 Jo P Mar 09

Calculus Application Problem #3 Name _________________________.docx
Calculus Application Problem #3 Name _________________________.docxCalculus Application Problem #3 Name _________________________.docx
Calculus Application Problem #3 Name _________________________.docx
humphrieskalyn
 

Similar to 27 Jo P Mar 09 (20)

Lecture 3
Lecture 3Lecture 3
Lecture 3
 
18 Jo P June 08
18 Jo P June 0818 Jo P June 08
18 Jo P June 08
 
26 Jo P Feb 09
26 Jo P Feb 0926 Jo P Feb 09
26 Jo P Feb 09
 
Java unit 3
Java unit 3Java unit 3
Java unit 3
 
Control All
Control AllControl All
Control All
 
02 Jo P Feb 07
02 Jo P Feb 0702 Jo P Feb 07
02 Jo P Feb 07
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 
Lecture 6
Lecture 6Lecture 6
Lecture 6
 
Types of c operators ppt
Types of c operators pptTypes of c operators ppt
Types of c operators ppt
 
C Programming Interview Questions
C Programming Interview QuestionsC Programming Interview Questions
C Programming Interview Questions
 
05 operators
05   operators05   operators
05 operators
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and Strings
 
C++ decision making
C++ decision makingC++ decision making
C++ decision making
 
Programming in Java: Control Flow
Programming in Java: Control FlowProgramming in Java: Control Flow
Programming in Java: Control Flow
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developers
 
Calculus Application Problem #3 Name _________________________.docx
Calculus Application Problem #3 Name _________________________.docxCalculus Application Problem #3 Name _________________________.docx
Calculus Application Problem #3 Name _________________________.docx
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and Strings
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 
20 Jo P Aug 08
20 Jo P Aug 0820 Jo P Aug 08
20 Jo P Aug 08
 
22 Jop Oct 08
22 Jop Oct 0822 Jop Oct 08
22 Jop Oct 08
 

More from Ganesh Samarthyam

More from Ganesh Samarthyam (20)

Wonders of the Sea
Wonders of the SeaWonders of the Sea
Wonders of the Sea
 
Animals - for kids
Animals - for kids Animals - for kids
Animals - for kids
 
Applying Refactoring Tools in Practice
Applying Refactoring Tools in PracticeApplying Refactoring Tools in Practice
Applying Refactoring Tools in Practice
 
CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”CFP - 1st Workshop on “AI Meets Blockchain”
CFP - 1st Workshop on “AI Meets Blockchain”
 
Great Coding Skills Aren't Enough
Great Coding Skills Aren't EnoughGreat Coding Skills Aren't Enough
Great Coding Skills Aren't Enough
 
College Project - Java Disassembler - Description
College Project - Java Disassembler - DescriptionCollege Project - Java Disassembler - Description
College Project - Java Disassembler - Description
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief PresentationBangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Brief Presentation
 
Bangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - PosterBangalore Container Conference 2017 - Poster
Bangalore Container Conference 2017 - Poster
 
Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)Software Design in Practice (with Java examples)
Software Design in Practice (with Java examples)
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
Bangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship DeckBangalore Container Conference 2017 - Sponsorship Deck
Bangalore Container Conference 2017 - Sponsorship Deck
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
Java Generics - Quiz Questions
Java Generics - Quiz QuestionsJava Generics - Quiz Questions
Java Generics - Quiz Questions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Software Architecture - Quiz Questions
Software Architecture - Quiz QuestionsSoftware Architecture - Quiz Questions
Software Architecture - Quiz Questions
 
Docker by Example - Quiz
Docker by Example - QuizDocker by Example - Quiz
Docker by Example - Quiz
 
Core Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quizCore Java: Best practices and bytecodes quiz
Core Java: Best practices and bytecodes quiz
 

Recently uploaded

Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
lizamodels9
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
dollysharma2066
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
Renandantas16
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
amitlee9823
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usage
Matteo Carbone
 
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pillsMifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Abortion pills in Kuwait Cytotec pills in Kuwait
 

Recently uploaded (20)

MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
 
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
Russian Call Girls In Gurgaon ❤️8448577510 ⊹Best Escorts Service In 24/7 Delh...
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 May
 
Grateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdfGrateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdf
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League City
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptx
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
 
7.pdf This presentation captures many uses and the significance of the number...
7.pdf This presentation captures many uses and the significance of the number...7.pdf This presentation captures many uses and the significance of the number...
7.pdf This presentation captures many uses and the significance of the number...
 
A DAY IN THE LIFE OF A SALESMAN / WOMAN
A DAY IN THE LIFE OF A  SALESMAN / WOMANA DAY IN THE LIFE OF A  SALESMAN / WOMAN
A DAY IN THE LIFE OF A SALESMAN / WOMAN
 
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf0183760ssssssssssssssssssssssssssss00101011 (27).pdf
0183760ssssssssssssssssssssssssssss00101011 (27).pdf
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Regression analysis: Simple Linear Regression Multiple Linear Regression
Regression analysis:  Simple Linear Regression Multiple Linear RegressionRegression analysis:  Simple Linear Regression Multiple Linear Regression
Regression analysis: Simple Linear Regression Multiple Linear Regression
 
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
KYC-Verified Accounts: Helping Companies Handle Challenging Regulatory Enviro...
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usage
 
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pillsMifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
 
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfDr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
 
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
 

27 Jo P Mar 09

  • 1. The Joy of Programming  | Guest Column  S.G. Ganesh How to Detect Integer Overflow Integer overflows often result in nasty bugs. In this column, we’ll look at some techniques to detect an  overflow before it occurs. I nteger overflow happens because computers use fixed if ( ((i + j) >  INT_MAX) || ((i + j) < INT_MIN) ) width to represent integers. So which are the operations      return 0; // wrong implementation that result in overflow? Bitwise and logical operations cannot overflow, while cast and arithmetic operations can. Why? Because (i + j) overflows, and when its result is For example, ++ and += operators can overflow, whereas && stored, it can never be greater than INT_MAX or less than or & operators (or even << and >> operators) cannot. INT_MIN! That’s precisely the condition (overflow) we Regarding arithmetic operators, it is obvious that operations want to detect, so it won’t work. like addition, subtraction and multiplication can overflow. How about modifying the checking expression? Instead How about operations like (unary) negation, division of ((i + j) > INT_MAX), we can check the condition (i > and mod (remainder)? For unary negation, -MIN_INT is INT_MAX - j) by moving j to the RHS of the expression. So, equal to MIN_INT (and not MAX_INT), so it overflows. the condition in isSafeToAdd can be rewritten as: Following the same logic, division overflows for the expression (MIN_INT / -1). How about a mod operation? It if( (i > INT_MAX - j) || (i < INT_MIN - j) ) does not overflow. The only possible overflow case (MIN_        return 0; INT % -1) is equal to 0 (verify this yourself—the formula for % operator is “a % b = a - ((a / b) * b)”). That works! But can we simplify it further? From Let us focus on addition. For the statement “int k = (i + j);”: condition (2), we know that for an overflow to occur, (1) If i and j are of different signs, it cannot overflow. the signs of i and j should be different. If you notice the (2) If i and j are of same signs (- or +), it can overflow. conditions in (3) and (4), the sign bit of the result (k) is (3) If i and j are positive integers, then their sign bit is zero. If k different from (i and j). Does this strike you as the check is negative, it means its sign bit is 1—it indicates the value that the ^ operator can be used? How about this check: of (i + j) is too large to represent in k, so it overflows. (4) If i and j are negative integers, then their sign bit is one. If int k = (i + j);  k is positive, it means its sign bit is 0—it indicates that the if( ((i ^ k) & (j ^ k)) < 0) value of (i + j) is too small to represent in k, so it overflows.     return 0; To check for overflow, we have to provide checks for conditions (3) and (4). Here is the straightforward Let us check it. Assume that i and j are positive conversion of these two statements into code. The function values and when it overflows, the result k will be isSafeToAdd returns true or false after checking for overflow. negative. Now the condition (i ^ k) will be a negative value—the sign bit of i is 0 and the sign bit of k is 1; so  /* Is it safe to add i and j without overflow?  ^ of the sign bit will be 1 and hence the value of the Return value 1 indicates there is no overflow; expression (i ^ k) is negative. So is the case for (j ^ k) else it is overflow and not safe to add i and j */  and when the & of two values is negative; hence, the int isSafeToAdd(int i, int j) { condition check with < 0 becomes true when there is    if( (i < 0 && j < 0) && k >=0) || overflow. When i and j are negative and k is positive,        (i > 0 && j > 0) && k <=0) ) the condition again is < 0 ( following the same logic        return 0; described above).    return 1; // no overflow - safe to add i and j  So, yes, this also works! Though the if condition is not } very easy to understand, it is correct and is also an efficient solution! Well, this does the work, but is inefficient. Can it be improved? Let us go back and see what i + j is, when it About the author: overflows. S G Ganesh is a research engineer in Siemens (Corporate Technology). His latest book is “60 Tips on Object Oriented If ((i + j) > INT_MAX) or if ((i + j) < INT_MIN), it Programming”, published by Tata McGraw-Hill. You can reach overflows. But if we translate this condition directly into him at sgganesh@gmail.com. code, it will not work: 12  |  March 2009 | LINUX For YoU | www.openITis.com