does a variable consume memory in addition to just its content (e.g. type, location)?

c, c++

Solution

The compiler will keep track of the properties of a variable - its name, lifetime, type, scope, etc. This information will exist in memory only during compilation. Once the program has been compiled and the program is executed, however, all that is left is the object itself. There is no type information at run-time (except if you use RTTI, then there will be some, but only because you required it for your program to function - such as is required for `dynamic_cast`ing).

Everything that happens in the code that accesses the object has been compiled into a form that treats it exactly as a single byte (because it's a `char`). The address that the object is located at can only be known at run-time anyway. However, variables with automatic storage duration (like local variables), are typically located simply by some fixed offset from the current stack frame. That offset is hard-baked into the executable.

Problem

Quite likely this has been asked/answered before, but not sure how to phrase it best, a link to a previously answered question would be great. If you define something like `char myChar = 'a';` I understand that this will take up one byte in memory (depending on implementation and assuming no unicode and so on, the actual number is unimportant). But I would assume the compiler/computer would also need to keep a table of variable types, addresses (i.e. pointers), and possibly more. Otherwise it would have the memory reserved, but would not be able to do anything with it. So that's already at least a few more bytes of memory consumed per variable. Is this a correct picture of what happens, or am I misunderstanding what happens when a program gets compiled/executed? And if the above is correct, is it more to do with compilation, or execution?

Original source