Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
}
question from:https://stackoverflow.com/questions/65852550/returning-an-empty-item-in-a-c-function-call

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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];
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...