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 225 views
1 answer 257 views
1 answer 275 views
1 answer 251 views
1 answer 260 views
1 answer 261 views
...