When learning C and C , I was told:
- that every variable has its own block of memory
- and the address of that chunk of memory never changes during the lifetime of the variable.
So I wonder those two statements are actually true? Is it possible to have variables that don't end up with their own memory?
For example
int a = 1
int b = a
in the above example, it is possible that any of the variables don't get their dedicated block of memory allocated? For example, when the variables are loaded directly into registers without being first stored in the memory?
CodePudding user response:
The C standard allows the C compiler to perform any optimization that has no observable effects.
If your C compiler can prove to itself that, for your example, using b as a mere alias for a will have no observable effects, then it is permitted, but not obligated, to compile this optimization which will have the effect of b not existing at all and not using any memory; and all references to b actually using a.
But you have absolutely no way to know that, except via external means such as using an external debugger, perhaps. If you had a way to know that, in the context of the C program, then, of course, making this optimization would have an observable effect and your C compiler will not do that.
CodePudding user response:
@SamVarshavchik is focusing on implementation.
But from the language point of view, only the register variables are guaranteed to do not have the reference (even if the implementation will place it in the memory). All other objects have references to them - thus they have representation in the memory.
The implementation might choose what to do with those objects (optimize them out, place them in the register, etc etc).
But if you use the reference to the object it will representation in the memory.
that every variable has its own block of memory and the address of that chunk of memory never changes during the lifetime of the variable.
It is the observable behaviour if the reference is used.
