1

When I write:

int a;
int c;

OR

int a, c;
  • When are a and c stored in adjacent places in the memory? ((&a+1) equals &c ?)
  • Does the way you define them has influence on this? Or it only depends on the machine?

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Also add that they might not even have a memory location at all.
Yes I know that array do so.. I was just wondering if it happens when I declare two ints like I did. Regarding the optimization, when would the compiler do such a thing?
@MarounMaroun When you don't take their address and they are either a constant or can stay inside a register.
@MarounMaroun Don't underestimate compilers. They can literally rewrite your code for you in ways that you can't even imagine. (if you're aren't familiar with them)
@MarounMaroun: if a variable is in a register, and your code uses it, then the compiler will emit CPU instructions that operate on that register. If you want to understand the instructions your compiler emits then it's probably worth your while spending a day or two on assembly language.
|
1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.