Program Ape's---C language details 7

Source: Internet
Author: User

Main content: Detection of two integral type addition whether overflow

#include <stdio.h> #include <limits.h>int main (int argc, char *argv[]) {/* *  A and B are nonnegative integer variables to detect if a+b will "overflow"  *  ///int_max=2147483647     INT a=123456789,b=2147483000;        /* Method One: if (a+b < 0)  printf ("overflow\n");      Cause of error: On some machines, the addition operation sets the internal register to four positive, negative, 0, and overflow. On this machine the C compiler has reason to detect, A and B add, and then check the internal register of the correlation flag is negative, but when the overflow occurs, the internal register state is overflow instead of negative, then overflow detection will fail/  //* The correct method is: Law one, Both A and B are coerced into unsigned integers; (reason: Because if you do not turn the words two number, if the addition result is greater than int_max words in the 32 register is signed, the sign bit is set 1, become negative, so it is impossible to more than Int_max, that is, detection is not out)  * /#if 1 if  ((unsigned) A + (unsigned) b > Int_max)//(unsigned) is required, Int_max is defined in limits.h, if not, implement  {//Int_max =2147483647  printf ("overflow\n");  } #else/* Method II, */if (a > Int_max-b)    //write this form can be used (unsigned) {printf ("overflow\n");} #endif  return 0;}

Output:


Program Ape's---C language details 7

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.