How to check if integer multiplication will overflow in C#

1 Answer

0 votes
using System;

class OverflowCheck
{
    static public bool multiplyWillOverflow(int x, int y) {
    	if (x == 0)
    		return false;
    
    	if (y > int.MaxValue / x)
    		return true;
    
    	if (y < int.MinValue / x)
    		return true;
    
    	return false;
    }

    static void Main()
    {
        int x = 3, y = 14727836;
        Console.WriteLine(multiplyWillOverflow(x, y) ? "true" : "false");

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



/*
run:

false
true

*/

 



answered May 18, 2025 by avibootz

Related questions

...