There is the following code:

int main() { int a = 1; int b = 2; printf("%d", &a - &b); return 0; } 

Question 1: Why is the address of the variable a greater than the address b.

Question 2: Why is the address difference 3?

3 answers 3

I hasten to please that the &a - &b construction in my opinion can work as you please. Logically, memory for variables a and b is allocated on the stack. Those. from older addresses to younger ones. And the memory should be allocated in the order of variable declarations. This is the answer to question 1.

Usually, variables on the stack are allocated in a row, without gaps. But here, how lucky, because Memory alignment can be enabled. And then all addresses of all objects will be multiple to some values ​​(for example, 8 bytes). Moreover, for me personally, the program displays the answer 1. This means that the difference in the addresses is equal to one element of the size of int. And what will happen if the compiler tries to optimize these instructions - generally a mystery. And try to find the difference with the program like this:

 #include <stdio.h> int main() { int a = 1; int b = 2; printf("%d", (char*)&a - (char*)&b); return 0; } 

Please note that the inclusion of the stdio.h header is necessary, otherwise the compiler may tear down the roof a little.

  • I use VS2010. Your program gave the answer 12. About the stack addressing, I do not quite understand, if not difficult to explain? Thanks for the answer. - thevoid 2012
  • A stack is a special way to store data. Have a good look at [wikipedia] [1]. You need to know that the function arguments are passed through the stack, and local variables are also stored as a stack. About 12 is easy. 3 * sizeof (int) = 3 * 4 = 12 [1]: ru.wikipedia.org/wiki/%D0%A1%D1%82%D0%B5%D0%BA - gecube

I have a difference in debug mode 8. In release 2 mode.

Debug overloads new delete and perhaps some low-level constructors for int or something like that.

That is, int a is first created; Then a temporary variable storing 1. then b then a variable for 2.

  • What the essence is the designer for int ? - gecube pm
  • Well, not a constructor, the debugging tools at the moment of compilation intercept the time of creating the variable and append the code that creates additional variables for their own needs. - manking

In x86 architecture, the stack grows from top to bottom. By the way, in the Spark architecture the stack grows the other way round: from smaller addresses to large ones, and the opposite picture will be observed there.

  • IMHO it depends more on the compiler than on the architecture. gcc.exe (GCC) 3.4.5 (mingw-vista special r3) in 32-bit XP gives 1, and gcc.real (Ubuntu / Linaro 4.6.3-1ubuntu5) 4.6.3 in the virtual machine on the same computer -1. Both results do not depend on the keys -O, -g - avp