What is the limit of int?

Scratchy Fo 20 Reputation points
2023-02-05T13:04:26.79+00:00

Hi all.

Looks like there's something I don't know... Net SDK 6.0.405, ASP Net Core 6.0.13.

But what is the real limit?

https://learn.microsoft.com/ru-ru/dotnet/csharp/language-reference/builtin-types/integral-numeric-types

I use:

int sqr = number * number; 

When I enter, for example, the numbers 999 and 9999 = I get the correct answers (998001 and 99980001).

When I enter 99999, I get 1409865409 instead of 9999800001.

But if y itself multiplies 99999 by 21000, I get 2099979000 which is less than 2147483648 (limit) and multiplied by the strength per cell. Where am I wrong?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,374 questions
0 comments No comments
{count} votes

Accepted answer
  1. Reza Aghaei 4,936 Reputation points MVP
    2023-02-05T20:13:48.5433333+00:00

    Actually 99999*99999 = 9,999,800,001 which is much greater than 2,147,483,647 which is int32.Max which results in an overflow. In C# the default context for arithmetic operations is unchecked context, which means in case of an overflow, no exception will be throws, and instead, the result will be truncated by discarding the high-order bits which doesn't fit.

    To change the default behavior, you need to run your arithmetic operation in a checked context.

    If you want to see the exception, you need can use checked like this:

    int number = 99999;
    int sqr = checked(number * number);
    

    Then you receive:

    System.OverflowException: 'Arithmetic operation resulted in an overflow.'
    

    If you want still use an integral type but still handle such large numbers, you may want to use long data type:

    long number = 99999;
    long sqr = checked(number * number);
    

    Which correctly calculate the result which is 9,999,800,001 and store it in the sqr variable.

    Learn more:

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful