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).