Programmer --- C language details 7

Source: Internet
Author: User

Programmer --- C language details 7
Main Content: checks whether the sum of two integer types overflows.

# Include

 
  
# Include

  
   
Int main (int argc, char * argv []) {/** a and B are non-negative integer variables, check whether a + B will "overflow" * // INT_MAX = 2147483647 int a = 123456789, B = 2147483000;/* Method 1: if (a + B <0) printf ("overflow \ n"); error cause: On some machines, the addition operation sets the internal register to four States: positive, negative, zero and overflow. On this machine, the c compiler has a reason to detect this; a and B are added, and then check whether the internal register-related flag is negative. However, when overflow occurs, if the internal register status is overflow rather than negative, the overflow detection will fail. * // the correct method is method 1. Convert both a and B to unsigned integers; (cause: If no conversion is made, the two numbers are added. If the addition result is greater than INT_MAX, the two numbers are signed in 32 registers, and the sign bit is set to 1, which turns to a negative number, in this case, it cannot be greater than INT_MAX, that is, it cannot be detected.) */# if 1 if (unsigned) a + (unsigned) B> INT_MAX) // (unsigned) is indispensable, INT_MAX in limits. defined in h. If not, implement it by yourself {// INT_MAX = 2147483647 printf ("overflow \ n ");} # else/* method 2, */if (a> INT_MAX-B) // you do not need to write this form (unsigned) {printf ("overflow \ n ");} # endif return 0 ;}

  

 

Output:


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.