Reputation: 95968
When I write:
int a;
int c;
OR
int a, c;
a
and c
stored in adjacent places in the memory? ((&a+1)
equals &c
?)Upvotes: 1
Views: 48
Reputation: 121397
There's no necessity to store the the ints a
and c
adjacently in either case. The C standard mandates no such thing.
Even if you observe such things, you can't rely on it for anything and is of no practical use.
Upvotes: 1
Reputation: 69663
The compiler is free to place them whereever it wants. There is no way to guarantee where they are placed. When you need them adjacent you can declare them as an array with two elements.
Upvotes: 1
Reputation: 53047
No, you cannot guarantee that a
and c
are in adjacent places in memory, but that is usually the case. I believe usually &a - 1
will be equal to &c
as the stack usually grows downwards.
If you want contiguous variables then use an array.
Does the way you define them has influence on this?
Usually the compiler won't reorder unless it has to. For instance to meet certain alignments or for performance reasons.
Also, as Mysticial says, the compiler can sometimes optimize variables out so they never exist in memory at all.
Upvotes: 3