Overflow during operation C# with Example



Overflow during operation C# with Example

Overflow also happens during the operation. In the following example, x is an int, 1 is an int by default. Therefore 
addition is an int addition. And the result will be an int. And it will overflow. 
int x = int.MaxValue; //MaxValue is 2147483647 
//It will be overflown 
long y = x + 1; 
Console.WriteLine(y); //Will print -2147483648 
//Same as Min value 
Console.WriteLine(int.MinValue); 
You can prevent that by using 1L. Now 1 will be a long and addition will be a long addition 
int x = int.MaxValue; //MaxValue is 2147483647 
long y = x + 1L; //It will be OK 
Console.WriteLine(y); //Will print 2147483648 

0 Comment's

Comment Form

Submit Comment