1

If I have:

int c = 100; 
float g = 22f;

when I debug the code the addresses where those variables are allocated are in reverse order compared to the order in which I wrote.

So, i.e, c is allocated at address 0x0086f910 and g is allocated at address 0x0086f904.

g is allocated before c but in the code I write c before g!

This not happen, for example, for array elements or structure members where the elements/members are allocated in the same order I put them.

Why that?

xdevel2000
  • 20,780
  • 41
  • 129
  • 196

2 Answers2

3

The compiler is allowed to do anything it wants with the storage of your variables. There is nothing in the spec to guarantee anything about this behaviour. Don't rely on it in your programs.

In contrast the order of fields within a structure and the order of elements in an array are mandated by the spec.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
3

C doesn't talk about how, where or in what order local variables are allocated; those are implementation details. From a language viewpoint the question is moot. An implementation could do the allocation in a completely random fashion that one couldn't correlate it to anything at all and still be conforming to the ISO C standard.

As for the implementation, on x86 the stack grows top-down i.e. newer stack frames, variables, etc. are allocated from higher memory addresses to lower ones. Again this is a convention, one could ignore it and write a compiler for x86 which could make the stack grow in the opposite direction.

Read Where the top of the stack is on x86, by a fellow stacker Eli Bendersky, for lots of details on this; it exactly addresses your confusion (although from an implementation viewpoint).

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222
  • is it the same for C language? – xdevel2000 Sep 18 '14 at 15:38
  • @xdevel2000, no it is not the same for C. C doesn't have a concept of constructors and destructors so this answer is meaningless in that context. – Carl Norum Sep 18 '14 at 15:39
  • 1
    Like Carl said, and I insist, the language doesn't have a play here i.e. both language specs don't mandate anything on the memory address front. Thus the question is invalid. C++ says about construction and deconstruction order of local variables, which has got nothing to do with your actual question. – legends2k Sep 18 '14 at 15:39
  • @CarlNorum Sorry, was hasty, reworded the answer for clarity. – legends2k Sep 18 '14 at 15:51