I am trying to understand static vs dynamic typing, but am really struggling to see how everything fits together.
It all starts with data types. As far as I understand, data types are quite abstract notions, which exist 'in' compilers in order to categorise data so that the operations on various types of data can be validated (i.e. in an attempt to stop you adding a string to an integer), and in order to generate the right machine code for the hardware interpretation of the value. I.e. say we have the following:
int myInt = 5;
char myChar = '5';
Console.WriteLine(myInt);
Console.WriteLine(myChar);
Both would ultimately write a five to the console window, but, since the representations in memory of integers and characters are different, the machine code which interprets the value in the memory location bound to the variable myInt
, which takes that value and displays it on the console window, would be different to the machine code for myChar
. Even though Console.WriteLine()
'does the same job', the different representations of five require different low level code.
So my question is this: if data types 'exist only in the compiler' - i.e. once the program has been compiled into machine code there is no knowledge of what type of data the value in a particular memory cell is (everything is just 1s and 0s) - then how can any type-checking be done at runtime? Surely there is no concept of data types at run time? So surely dynamic typing can't be anything to do with type-checking occurring at run time?
Where is my understanding going wrong, and could somebody please explain static and dynamic typing with respect to the argument given above? What is the big picture of what is going on?
I am trying to understand this for an essay, so references to books or online sources would be useful :) Thank you.