Can a pointer (address) ever be negative?

前端 未结 13 1742
情书的邮戳
情书的邮戳 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:32

    What's the difference between failure and unitialized. If unitialized is not another kind of failure, then you probably want to redesign the interface to separate these two conditions.

    Probably the best way to do this is to return the result through a parameter, so the return value only indicates an error. For example where you would write:

    void* func();
    
    void* result=func();
    if (result==0)
      /* handle error */
    else if (result==-1)
      /* unitialized */
    else
      /* initialized */
    

    Change this to

    // sets the *a to the returned object
    // *a will be null if the object has not been initialized
    // returns true on success, false otherwise
    int func(void** a);
    
    void* result;
    if (func(&result)){
      /* handle error */
      return;
    }
    
    /*do real stuff now*/
    if (!result){
      /* initialize */
    }
    /* continue using the result now that it's been initialized */
    

提交回复
热议问题