Question:
Computer Stack?
Brock Lee
2008-04-08 10:44:49 UTC
Ok, I've been doing research on the "stack" of a computer and I think I get how it works. It pushes a number down onto the stack and than pops that number off later.

What I don't understand is where this would be useful. Can you show me any examples?
Four answers:
recentcoin2000
2008-04-08 10:51:13 UTC
You mean like a TCP/IP stack.....
Courtne{Y}
2008-04-08 18:01:55 UTC
This is useful for many different reasons. Local variables to a function is an example. Everytime you declare a variable the compiler will subtract the size of the variable from the stack pointer ( ESP on x86/64-bit machines ).



Example:

void function ( void ){

int i = 0;

}



Or calling functions causes information to be pushed onto a thread's stack, such as return address, arguments passed.



Example:

void function (void){

int i = 5;

somefunction(i);

}



There are many uses for a stack, these are just uses that a language and machine will use them for. To see how a machine uses it you can always look at some disassembled code and view how functions are called or how variables are accessed or arguments.

( I left out what those examples might look like disassembled )
cja
2008-04-08 18:02:00 UTC
The stack is used to pass arguments to a function, and for space needed by automatic variables declared inside a function. The ability to pass arguments to a function, and to declare automatic variables, are very useful features.



The stack as a data structure can be useful for implementing a variety of algorithms. For an RPN calculator, for example, given the equation: x y +

you would push operand x, then push y. When you get to an operator you pop operands to evaluate.
joetcochran
2008-04-08 17:54:33 UTC
Stacking mechanisms are useful in programming when you have a program that goes several function calls deep.



function A calls function B, which calls function C



So when you get into function C, your stack looks like this

(top of stack)

function C

function B

function A

(bottom of stack)



When function C ends, it needs to know where to return to. It "pops" function C off the top of the stack, and function B's new position is at the top.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...