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?
I guess this isn’t strictly programming, but I’ve been pondering this for a little
Share
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
xis anint, 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”).