How to check if integer addition will overflow in C#

1 Answer

0 votes
using System;

class OverflowCheck
{
    public static bool AddingWillOverflow(int x, int y) {
        return ((x > 0) && (y > int.MaxValue - x)) || ((x < 0) && (y < int.MinValue - x));
    }

    static void Main()
    {
        int x = 39839299, y = 1472783642;
        Console.WriteLine(AddingWillOverflow(x, y) ? "true" : "false");

        x = 1338839299; y = 1872783642;
        Console.WriteLine(AddingWillOverflow(x, y) ? "true" : "false");
    }
}



/*
run:

false
true

*/

 



answered May 17, 2025 by avibootz

Related questions

1 answer 133 views
1 answer 153 views
1 answer 189 views
1 answer 172 views
1 answer 181 views
1 answer 178 views
...