Section81.1:Integeroverflow
Thereisamaximumcapacityanintegercanstore.Andwhenyougooverthatlimit,itwillloopbacktothenegative side. For int, it is 2147483647
intx=int.MaxValue; //MaxValueis2147483647
x=unchecked(x+1); //makeoperationexplicitlyuncheckedsothattheexamplealso
workswhenthecheckforarithmeticoverflow/underflowisenabledintheprojectsettings Console.WriteLine(x); //Willprint-2147483648 Console.WriteLine(int.MinValue); //SameasMinvalue
ForanyintegersoutofthisrangeusenamespaceSystem.NumericswhichhasdatatypeBigInteger.Checkbelow linkformoreinformationhttps://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx
Section81.2:Overflowduringoperation
Overflowalsohappensduringtheoperation.Inthefollowingexample,xisanint,1isanintbydefault.Therefore addition is an intaddition. And the result will be an int.And it will overflow.
intx=int.MaxValue; //MaxValueis2147483647
longy=x+1; //Itwillbeoverflown
Console.WriteLine(y); //Willprint-2147483648
Console.WriteLine(int.MinValue); //SameasMinvalue
Youcanpreventthatbyusing1L.Now1willbealongandadditionwillbealongaddition
intx=int.MaxValue; //MaxValueis2147483647
longy=x+1L; //ItwillbeOK
Console.WriteLine(y); //Willprint2147483648
Thereisoverflowinthefollowingcode
intx=int.MaxValue;
Console.WriteLine(x+x+1L); //prints-1
Whereasinthefollowingcodethereisno overflow
intx=int.MaxValue;
Console.WriteLine(x+1L+x); //prints4294967295
Thisisduetotheleft-to-rightorderingoftheoperations.Inthefirstcodefragmentx+xoverflowsandafterthatit becomesalong.Ontheotherhandx+1Lbecomeslongandafterthatxisaddedtothisvalue.
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024