Reputation: 1000
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.
Upvotes: 3
Views: 1581
Reputation: 1132
Yes. A declared variable occupies space. And sizeof
operator returns size of short data type.
Also if you have not used "a
" after declaring — for example, you don't initialize it or use it anywhere else in the code — there could be a chance for the compiler to optimize it away.
Upvotes: 0
Reputation: 15091
That depends on many factors.
First of all, optimizer may (or may not) drop that variable completely. Though it's not really the case in your piece of code, if you really use it in printf
call (which is UB, as others did note).
Next, what do you mean by "occupy memory"? Here compiler most probably will use a piece of stack memory, which anyway should be reserved for the process earlier. And if it wouldn't be inside main()
, then that memory would have been freed upon function return. So it's not really a "practical" waste.
I thought the '0' meant no memory was yet initialized
Nope. When one says "initialized", he means "initialized to some known value". On the other hand, "uninitialized" doesn't mean "non-zero", but rather "some garbage" / "I don't know" / "I don't care" etc.
Upvotes: 1
Reputation: 106012
When you declared short a;
, compiler allocate memory for a
and this memory contains some indeterminate value. In this case it might be 0
and that's what you are getting, but the behavior of program is undefined and nothing can be said.
Upvotes: 1
Reputation: 17339
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
.
Upvotes: 3
Reputation: 206607
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.
Upvotes: 1