Welcome to OGeek Q&A 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...