Does initializing a member variable and not referencing/using it further take up RAM during runtime, or does the compiler simply ignore that variable?
struct
The examples provided by other answers to this question which elide var2
are based on a single optimization technique: constant propagation, and subsequent elision of the whole structure (not the elision of just var2
). This is the simple case, and optimizing compilers do implement it.
For unmanaged C/C++ codes the answer is that the compiler will in general not elide var2
. As far as I know there is no support for such a C/C++ struct transformation in debugging information, and if the struct is accessible as a variable in a debugger then var2
cannot be elided. As far as I know no current C/C++ compiler can specialize functions according to elision of var2
, so if the struct is passed to or returned from a non-inlined function then var2
cannot be elided.
For managed languages such as C#/Java with a JIT compiler the compiler might be able to safely elide var2
because it can precisely track if it is being used and whether it escapes to unmanaged code. The physical size of the struct in managed languages can be different from its size reported to the programmer.
Year 2019 C/C++ compilers cannot elide var2
from the struct unless the whole struct variable is elided. For interesting cases of elision of var2
from the struct, the answer is: No.
Some future C/C++ compilers will be able to elide var2
from the struct, and the ecosystem built around the compilers will need to adapt to process elision information generated by compilers.