PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How to compare sum of two int64 with INT64_MAX?

 July 20, 2022     c++, integer     No comments   

Issue

I know number greater than INT64_MAX will wrap around negative, So how to compare when sum overflow, that is sum greater than INT64_MAX.

#include <iostream>

using namespace std;

int main() {
  int64_t a = INT64_MAX;
  int64_t b = 1;
  // cin >> a >> b;
  if (a + b <= INT64_MAX) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }
  return 0;
}

Solution

First compare b to either INT64_MIN - a or INT64_MAX - a before the addition to prevent undefined behavior (UB) of signed integer overflow.

// True when sum overflows.
bool is_undefined_add64(int64_t a, int64_t b) {
  return (a < 0) ? (b < INT64_MIN - a) : (b > INT64_MAX - a);
}

Worst case: 2 compares.

For div, mul, sub



Answered By - chux - Reinstate Monica
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing