In this short example, a question from an exam I had yesterday:
int main() {
short a;
}
Does 'a' occupy any memory space? When I made:
printf("%u %d\n",a, sizeof(a));
I get printed a '0 2' so I thought the '0' meant no memory was yet initialized but my teacher says yes, it occupies 2 bytes already.
Thanks, Dani.
The correct answer is 'maybe'. The compiler must give you the illusion that it does occupy memory, and in most practical cases it will.
However, the compiler is free to do what it wants as long as it maintains that illusion. In your example without the printf, the variable a is never used. The compiler is free to optimize it out, so it might not use any memory. Indeed that often happens when you enable optimization flags, such as -O3 for gcc.
Does an initialized variable occupies memory?
Yes. I am guessing you meant to use uninitialized there. The answer is still Yes.
When you use the value of an uninitialized variable, like in the call to printf, the program is subject to undefined behavior.
However, sizeof(a) is computed at compile time. It does not depend on whether the variable is initialized or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With