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

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...