Seite 1 von 1

No overflow in variables?

Verfasst: Mittwoch 22. Januar 2014, 19:17
von blcfpp
Hi everyone. First of all sorry if my English is not good.
I have a question about something in Python I can not explain:
in every programming language I know (e.g. C#) if you exceed the max-value of a certain type (e.g. a long-integer) you get an overflow. Here is a simple example in C#:

Code: Alles auswählen

        static void Main(string[] args) 
        { 
            Int64 x = Int64.MaxValue; 
            Console.WriteLine(x);       // output: 9223372036854775807 
            x = x * 2; 
            Console.WriteLine(x);       // output: -2 (overflow) 
            Console.ReadKey(); 
        } 
Now I do the same with Python:

Code: Alles auswählen

            x = 9223372036854775807 
            print(type(x))            #   <class 'int'> 
            x = x * 2                    
            print(x)                     #   18446744073709551614              
            print(type(x))            #   <class 'int'>
and I get the right output without overflow and the type is always a 'int'.
How does Python manages internally the types and their values? Where are they stored?

Thank you for your help :)

Re: No overflow in variables?

Verfasst: Mittwoch 22. Januar 2014, 19:26
von BlackJack
@blcfpp: The values are stored in memory. ;-) And the `int` type is just limited by available memory and not by some arbitrary fixed constraints¹. Instead of, say 8 bytes per integer value, Python uses a variable amount of bytes, at least as much as needed to represent the value of an `int` instance.

The CPython implementation is OpenSource, so you can have a look how the type is implemented.

____
¹ Well, technically this is not true, but the limit is way above what fits into memory on most computers, even ones with much memory.

Re: No overflow in variables?

Verfasst: Mittwoch 22. Januar 2014, 19:29
von blcfpp
Thank you :)