Default argument in a function [C++]

I tried to do something like this:

int& g(int& number = 0)
{
//maybe do something with number
    return number;
}

but it doesn't work. It has to be passed by reference. Thank you for any help.

P.S. I think that "Related Questions" appearing once you type Title is a good idea, but I also think that they should be displayed only if they are related to specific language, i.e. it is less than useless for me to looking at topic with similar problem but in Ruby.

Upvotes: 3

Views: 571

Answers (4)

emvee
emvee

Reputation: 4449

Your idiom is wrong.

A global function should basically never return a reference - other than e.g. hiding a global variable. That case is acceptable, however, the usage is questionable: if the variable was already global, why hide it behind a functioncall?

If your goal is to modify the argument, then why give a returnvalue? Only usefull if you e.g. return the old value - and that has to be done "by value" rather than "by reference".


int g(int& arg) {
   int oldarg( arg );
   // maybe modify arg
   // return old value of arg
   return oldarg;
}

or:


const int& g(int& arg) {
    static int accumulator;
    accumulator += arg;
    return accumulator;
}

Where, in the latter case, passing argument by reference and/or returning the accumulator by reference is unnecessary.

cheers, h.

Upvotes: 0

visitor
visitor

Reputation: 8834

A non-const reference cannot bind to a temporary (literal).

Here it would probably make most sense to take arguments and return by value, and leave it up to the caller to assign the result back to the variable (if they want so): k = g(k);

Perhaps you could also use two overloads, but the "default" one cannot return by reference, which might lead to some confusion:

int& g(int&);

int g()
{ 
    int arg = 0;
    return g(arg);
}

Upvotes: 0

GManNickG
GManNickG

Reputation: 503873

You have a non-const reference, which means you can modify the referand. But your default is the constant 0.

Does it really make sense for this function to have a default?

Upvotes: 4

anon
anon

Reputation:

If you really want to do this:

  • make the reference const, so that a temporary can be bound to it
  • put the default in the function declaration, not the definition

For example:

// header
const int & g( const int & number = 0 );


// implementation
const int & g( const int & number )
{
//maybe do something with number
    return number;
}

PS Post your complaints about how SO works on Meta, not here (for all the good it will do - answering this question indicated they STILL haven't fixed the code-after-list bug)

Upvotes: 11

Related Questions