What would be a proper invalid value for a pointer?

风格不统一 提交于 2019-12-02 07:05:06
void fun()
{
   // calculate what ptr value should be
   const char* ptr = /*...*/;

   // now handle ptr normally
   fun(ptr);
}

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)

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
}
Haatschii

You should use the nullptr for that. Its new in the C++11 standart. Have a look here for some explanation.

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);

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) ....
}

1?

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!