Reputation: 51
I am studying a course on data structures and currently I am stuck with something in stacks. In the implementation of StackTop
function (which makes a copy or "returns in a sense" the top element in the stack without affecting the stack.) The below code is the implementation of it and it is clear,
void StackTop(StackEntry *pe, Stack *ps){
*pe=ps->entry[ps->top-1];
}
but as long as we want to give the user the value of top element in the stack couldn't we make the function like this ? And if so then what's the difference between these two implementations ?
StackEntry StackTop(Stack *ps){
return ps->entry[ps->top-1];
}
Keep in mind that StackEntry
is a user-defined data type.
Upvotes: 2
Views: 166
Reputation: 311048
The both functions have no good design. The problem of the both functions is that the stack can be empty. In this case the functions have undefined behavior and it is difficult to determine whether it is the case.
In C a better function definition can look like
int StackTop( Stack *ps, StackEntry *pe )
{
int success = ps->top != 0;
if ( success )
{
*pe = ps->entry[ps->top-1];
}
return success;
}
If you do not bother about the undefined behavior of the functions because there is one more function that reports whether the stack is empty then you should consider one more function implementation that will allow to change the value stored in the stack. Such a function can look like
StackEntry * StackTop(Stack *ps)
{
return &ps->entry[ps->top-1];
}
Upvotes: 2
Reputation: 224342
Either one can be used. The main difference is the number of copies done.
In the first case the resulting value is written directly to the target variable via a pointer dereference. In the second case the value is (in most implementations) put on the stack, then copied to the variable receiving the return value, assuming the return value is assigned.
For the return value case, given that a struct is being returned, the compiler is probably not copying the return value to the stack but to some other location and putting a pointer to that location on the stack. This is entirely up to the implementation however. In either case, the struct data is being copied twice. If the struct is relatively small there shouldn't be a measurable difference, although it could become significant if the struct is several megabytes large.
Upvotes: 3