What would be a proper invalid value for a pointer?

前端 未结 7 581
抹茶落季
抹茶落季 2021-01-25 03:16

Suppose I have this code. Your basic \"if the caller doesn\'t provide a value, calculate value\" scenario.

void fun(const char* ptr = NULL)
{
   if (ptr==NULL) {         


        
相关标签:
7条回答
  • 2021-01-25 03:33

    If you want a special value that corresponds to no useful argument, make one.

    header file:

    extern const char special_value;
    
    void fun(const char* ptr=&special_value);
    

    implementation:

    const char special_value;
    
    void fun(const char* ptr)
    {
        if (ptr == &special_value) ....
    }
    
    0 讨论(0)
  • 2021-01-25 03:39
    void fun()
    {
       // calculate what ptr value should be
       const char* ptr = /*...*/;
    
       // now handle ptr normally
       fun(ptr);
    }
    
    0 讨论(0)
  • 2021-01-25 03:50

    I agree with all the other answers provided, but here's one more way of handling that, which to me personally looks more explicit, if more verbose:

    void fun()
    {
      // Handle no pointer passed
    }
    
    void fun(const char* ptr)
    {
      // Handle non-nullptr and nullptr separately
    }
    
    0 讨论(0)
  • 2021-01-25 03:51

    Using overloaded versions of the same function for different input is best, but if you want to use a single function, you could make the parameter be a pointer-to-pointer instead:

    void fun(const char** ptr = NULL) 
    { 
       if (ptr==NULL) { 
          // calculate what ptr value should be 
       } 
       // now handle ptr normally 
    } 
    

    Then you can call it like this:

    fun();
    

    .

    char *ptr = ...; // can be NULL
    fun(&ptr);
    
    0 讨论(0)
  • 2021-01-25 03:51

    1?

    I can't imagine anyone allocating you memory with that address.

    0 讨论(0)
  • 2021-01-25 03:54

    Depending on your platform, a pointer is likely either a 32 or 64-bit value.

    In those cases, consider using:

    0xFFFFFFFF or  0xFFFFFFFFFFFFFFFF
    

    But I think the bigger question is, "How can NULL be passed as a valid parameter?"

    I'd recommend instead having another parameter:

    void fun(bool isValidPtr, const char* ptr = NULL)
    

    or maybe:

    void fun( /*enum*/ ptrState, const char* ptr = NULL)
    
    0 讨论(0)
提交回复
热议问题