No overflow in variables?

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
blcfpp
User
Beiträge: 2
Registriert: Mittwoch 22. Januar 2014, 18:37

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 :)
Zuletzt geändert von Anonymous am Mittwoch 22. Januar 2014, 19:27, insgesamt 1-mal geändert.
Grund: Code tags around source code
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.
blcfpp
User
Beiträge: 2
Registriert: Mittwoch 22. Januar 2014, 18:37

Thank you :)
Antworten