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) {
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) ....
}
void fun()
{
// calculate what ptr value should be
const char* ptr = /*...*/;
// now handle ptr normally
fun(ptr);
}
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
}
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);
1?
I can't imagine anyone allocating you memory with that address.
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)