Reputation: 44668
I guess this isn't strictly "programming", but I've been pondering this for a little while. When you create a variable and assign it a value, the computer allocates a certain number of bytes for said variable and stores the value, but how does it know what type of data is in that memory address when it comes back to use it later?
Upvotes: 7
Views: 2144
Reputation:
Generally, it doesn't. Well, most dynamic languages have something like typeof
, so usually there's an "object header" storing some metadata, including type (and other information, e.g. refcount). But you still can't identify the start of an object in a random chunk of memory (it's all 1s and 0s, after all), so you need a pointer to it at all times...
Traditional static/compiled languages (usually, of course) don't store such information. After all, if compiler knows that x
is an int
, it knows how many bytes it needs to load into registers and which opcodes to use for additon. Even when you add virtual functions, you merely need to compile a table of function pointers (with no further metadata needed - obj->foo()
translates to "fetch nth entry of vtable and call it" instead of "call code at this address").
Upvotes: 6
Reputation: 19981
The answer depends on whether the language you're working in is interpreted or compiled, and on various other details. For a compiled language like C, the answer is that the compiler, while it's translating your code into machine code (or assembler), has an internal data structure saying what every variable is -- what its type is, where it's stored, and probably other information too for optimization purposes. (But by the time your code is actually being run, that information is all gone; it's needed to compile your code but not to run it.)
For some interpreted languages, the answer is that the interpreter has a similar data structure which is looked up whenever the variable is used. For others, all variables are treated the same way by the interpreter but their values have type information attached to them.
Upvotes: 7
Reputation: 198334
The computer doesn't. Some languages might tag their data with types (specifically, the dynamic languages, where any variable can hold any data type); in other languages (like C), you declare variables, and the compiler knows whenever it uses the address space associated with that variable to treat the value as a specific type. Computer itself doesn't care, all it sees is 8 bits per byte.
Upvotes: 4