Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 290
  • Last Modified:

Passing default argument as a pointer

fun(int *p)

int main()
int i;

In the above function I want to initialize the value of i as 99, with the concept of default argument in C++. ie. the content of p or *p will be 99 in the function fun().Here I am passing argument as a pointer to the int variable so how to do that?
1 Solution
When you use a default argument you do not pass anything in.  Also, you cannot default the dereferenced result of a pointer, so you'll have to change int* p to just int p.  If you need a pointer for a return value you'll have to add a second parameter for that (one for the default initial value, one for the pointer for the return value).

In the header declare fun as:

fun(int p = 99);

Then in main,

int main()

This will use 99 in the fun function.

If I understand what you want correctly, you cannot use default-argument syntax for this.
But you could use function overloading instead:

void f(int* p) { /* do stuff */ }
void f()
  int i = 99;


void f(int* p=0) // pass NULL pointer by default;
  int default_int = 99;
  if( p == 0 ) p = &default_int;

  /* do stuff */

I hope this helps,
FrancozAuthor Commented:
The second answer by ivec seems to be a better choice. But it is a logical method, where I'm seeking one standard C++ method. So I'll explain my qn further.

I'll be passing one pointer to an integer into the function f() as follows.

void f(int *p)
//doing something

But while calling f() I need the content of p to be initialised with 99, if nothing is passed specifically.

Please note down the point if nothing is passed.

Why I mentioned default argumets, because say if it was a normal int variable then I can have declaration like this.

void f(int i = 99)
//do something.

More than that I wish to do this without an extra cost of function overloading etc.

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now