Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ doesn't require a stack?

The first time a teacher had introduced me to C++, one of the first definitions was about "stack based languages" like Java, C and C++.

Now i read about this in a reply and I'm honestly confused.

C++ is a stack based language but doesn't requires a stack ?

like image 518
user1797612 Avatar asked Dec 14 '12 03:12

user1797612


2 Answers

C++ (like C, Java, and most other block-structured languages) requires a "stack" in the sense of some sort of last-in, first-out data structure to hold the activation records for function calls. That is, a function can call itself recursively to some arbitrary depth, and as it does so, the parameters/local variables for each call must be independent of those for previous calls. As those function calls return, the parameters/local variables for each must be destroyed.

That does not, however, require execution on a CPU that directly supports a stack in hardware. It's entirely possible to execute C++ (and the other block-structured languages, as mentioned above) without direct hardware support for a stack.

Just for example, early Crays and (even current) IBM mainframes do not support stacks. Despite this, they can and do support C++. At least in most cases, the LIFO data structure used for activation records is allocated dynamically, and build into a linked list. As each function is called, its activation record is allocated and added to the linked list. When the function returns, that activation record is removed from the list and the memory released.

So, if you're looking at things from a somewhat abstract viewpoint, thinking of a stack as the essence of the basic operations it provides, then yes, C++ requires a stack. If you look at "stack" less abstractly, and think in terms of something like a CPU with a stack pointer register (or anything on that order) then no, C++ definitely does not need a stack (and the same goes for C, Java, etc.)

like image 94
Jerry Coffin Avatar answered Oct 31 '22 23:10

Jerry Coffin


When I hear "stack based language" I usually think of languages like FORTH where everything is done on a stack, ie no variables. I'm guessing when your teacher said Java they meant the JVM which is stack based.

Now, the C++ standard has absolutely no concept of a stack or heap, only things like automatic and dynamic storage. C++ is specified in terms of more abstract ideas which allows it to theoretically work on many different implementations and hardware. Of course, it turns out that these ideas map directly onto the idea of a stack, so every implementation ends up using one.

like image 31
Pubby Avatar answered Oct 31 '22 23:10

Pubby