Stack
5 messages in this thread
I'm a little unfamiliar with some terms that I've come across. To begin
with, what is a stack and how is it used in C?
Chris
Chris,
A STACK, in any computer language, is a section of memory that is used to
hold information (like addresses) for use in a program. It is usually
arranged so that items are put one on top of the other in memory – that is,
they read from the bottom up. And the items stored there are taken off in
opposite order to that in which they were put on. For example, if you put
an address there, went to another location in memory to do something, and
then wanted to return to where you left off, the address you stored would
be at the top of the stack, so you would pull it off the stack and go to
that address. I hope this makes sense to you.
Betty
It sort of makes sense. What would be a typical usage of the stack? Is it
mainly for storing addresses or numbers for near future use?
Chris
Chris,
A stack is used to store return addresses, so that when one routine
calls another, when that 2nd routine is done…the program knows where to
return to so it can continue. The stack is also used to pass values from
one routine to another. So that if routine1 needs to send a value to
routine2, it simply puts it on the stack. routine2 has been created so
that it knows to read that value off of the stack.
A stack is also used to create what are known as 'local variables',
that is…variables that are created and used within a single routine.
That's a very simplistic explanation, but there's not room here to
give a full and complete description of stack usage with examples. However,
hopefully it gives you a bit of a better idea of how it's used and why.
Don
The stack can be used to store any kind of data so long as you know that
the last item put on the stack will be the first one you need to take off.
So – it might be addresses or it might be data, depending upon the order
in which you would need things.
Betty