How to check if integer addition will overflow in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

// math.MaxInt64 = 9223372036854775807

func addingWillOverflow(x, y int64) bool {
    return ((x > 0) && (y > math.MaxInt64 - x)) || 
           ((x < 0) && (y < math.MinInt64 - x))
}

func main() {
    x, y := int64(39839299), int64(1472783642)
    fmt.Println(addingWillOverflow(x, y))
    
    x, y = int64(9223372036854775807), int64(10)
    fmt.Println(addingWillOverflow(x, y))
}


 
/*
run:

false
true
 
*/

 



answered May 17, 2025 by avibootz

Related questions

...