xnerdx
October 4th, 2010, 08:23 PM
I'm reading the book Practical C++ Programming and it's currently stepping into discussing simple classes. To convey the idea it's describing how to create a simple stack using structures and later it will discuss preforming the same action with classes. I understand both classes and structures but I'm curious about whether this code is writen correctly. The following code is quoted from the book, I don't own any of the following code:
**Structure declaration**
const int STACK_SIZE = 100; // Maximum size of a stack
// The stack itself
struct stack {
int count; // Number of items in the stack
int data[STACK_SIZE]; // The items themselves
};
**Pop function**
inline int stack_pop(struct stack& the_stack)
{
// Stack goes down by one
--the_stack.count;
assert((the_stack.count >= 0) &&
(the_stack.count <
sizeof(the_stack.data)/sizeof(the_stack.data[0])));
// Then we return the top value
return (the_stack.data[the_stack.count]);
}
I haven't tested it but my assumption is that using the stack_pop function will return the 2nd vaule in the stack, not the first; seeing as the stack count is decremented by one prior to determining the top most item. Is my assumption correct or am I looking at this the wrong way...
EDIT: I figured it out... I feel stupid now. The "top-most" data member (the member at count prior to decrementing the count by one) is not set to anything yet. The push function allocates a new, empty data spot after it's called. Therefore, the top-most (existing) data member is at [count-1]. I apologize for posting without thinking :'(. Hopefully someone can benifit...
**Structure declaration**
const int STACK_SIZE = 100; // Maximum size of a stack
// The stack itself
struct stack {
int count; // Number of items in the stack
int data[STACK_SIZE]; // The items themselves
};
**Pop function**
inline int stack_pop(struct stack& the_stack)
{
// Stack goes down by one
--the_stack.count;
assert((the_stack.count >= 0) &&
(the_stack.count <
sizeof(the_stack.data)/sizeof(the_stack.data[0])));
// Then we return the top value
return (the_stack.data[the_stack.count]);
}
I haven't tested it but my assumption is that using the stack_pop function will return the 2nd vaule in the stack, not the first; seeing as the stack count is decremented by one prior to determining the top most item. Is my assumption correct or am I looking at this the wrong way...
EDIT: I figured it out... I feel stupid now. The "top-most" data member (the member at count prior to decrementing the count by one) is not set to anything yet. The push function allocates a new, empty data spot after it's called. Therefore, the top-most (existing) data member is at [count-1]. I apologize for posting without thinking :'(. Hopefully someone can benifit...