0

Why the addresses of stack variables grow backwards in C++? If so, what is the benefit of such design? Is it specific to clang/llvm?

More specifically, when I run the following program,

#include <iostream>

void f(int n, int* first_v) {
    int v = 0;
    if (first_v == NULL) {
        first_v = &v;
    }
    std::cout << "(offset=" << ((int)&v - (int)first_v) << ") ";

    if (n<=0) return;
    f(n-1, first_v);
}

int main() {
    f(3, NULL);
}

the output is

(offset=0) (offset=-48) (offset=-96) (offset=-144) 

(click here http://codepad.org/nTs0jgr3 to run online)

PS. Pardon for not using Modern C++ strictly (Use of NULL and *), null_ptr was not available in the compiler I was testing.

PS. Q: Is it really backwards, or is it an artifact of conversion of pointer type int* to signed int? A: At least we can say the direction of stack is opposite of the conventions for loops/iterators, ie the ++ operator of a for loop that uses a pointer. Which is a convention (ie, a C implementation can compile it backwards).

Sohail Si
  • 2,750
  • 2
  • 22
  • 36
  • 6
    C++ has no say over this. This is how the hardware/CPU works. As far as the reason for that, it's historical in nature. – Sam Varshavchik Jun 12 '22 at 16:36
  • 1
    Comparing the address of objects like this is UB. – Martin York Jun 12 '22 at 17:58
  • 1
    Comparing two pointers that don't point to parts of the same object (in this case, comparing the addresses of distinct `ints`s that have no particular relationship in memory to each other) gives undefined behaviour. Even ignoring that (for sake of discussion only) converting a pointer to an `int` is not guaranteed to preserve value (or relationship between values) so converting two pointers to `int` and then subtracting is not necessarily meaningful. – Peter Jun 13 '22 at 03:11

0 Answers0