Can a pointer (address) ever be negative?

前端 未结 13 1691
情书的邮戳
情书的邮戳 2020-11-29 05:53

I have a function that I would like to be able to return special values for failure and uninitialized (it returns a pointer on success).

Currently i

13条回答
  •  一生所求
    2020-11-29 06:14

    It's generally a bad design to try to multiplex special values onto a return value... you're trying to do too much with a single value. It would be cleaner to return your "success pointer" via argument, rather than the return value. That leaves lots of non-conflicting space in the return value for all of the conditions you want to describe:

    int SomeFunction(SomeType **p)
    {
        *p = NULL;
        if (/* check for uninitialized ... */)
            return UNINITIALIZED;
        if (/* check for failure ... */)
            return FAILURE;
    
        *p = yourValue;
        return SUCCESS;
    }
    

    You should also do typical argument checking (ensure that 'p' isn't NULL).

提交回复
热议问题