samuelbrody1249
samuelbrody1249

Reputation: 4767

Returning an empty item in a C function call

I want to return the last in a stack. Something like the following:

Item* get_last_item()
{
    if (item_stack_size == 0) {
        // return <nothing> ?
    }  else {
         return ItemStack[item_stack_size-1];
    }
}

What is the suggested practice when returning the equivalent of a null value if the stack is empty? Should this usually issue a hard error? Something like a value of (Item*) 0, or what's the suggested practice for doing something like this? My first thought was to do something like this, but I'm not sure if there's a better way:

Item* get_last_item()
{
    return (item_stack_size != 0) ? ItemStack[item_stack_size-1] : (void*) 0;
}

Upvotes: 0

Views: 34

Answers (1)

wildplasser
wildplasser

Reputation: 44240

For functions returning a pointer, a NULL pointer can be used as an out of band value( the caller of course should check the pointer for NULL, before dereferencing it):


Item *pop_last_item()
{
    if (!item_stack_size) {
        return NULL;
    }  else {
         return ItemStack[--item_stack_size];
    }
}

Upvotes: 1

Related Questions