The default argument to the function [C ++]

I tried to do something like this:

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

but that will not work. It must be passed by reference. Thanks for any help.

PS I think that “related questions” appear after you type “Heading”, this is a good idea, but I also think that they should only be displayed if they are related to a certain language, that is, for me less than useless to search for a topic with a similar problem but in Ruby.

+3
source share
4 answers

If you really want to do this:

  • make a const link so that time can be bound to it
  • ,

:

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


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

PS , SO Meta, ( ), , , STILL .

+11

, , referand. 0.

, ?

+4

().

, , , ( ): k = g(k);

, , " " , :

int& g(int&);

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

.

- , , . , : , ?

- , returnvalue? , , . - " ", " ".


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

:


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

/ .

, .

0

Source: https://habr.com/ru/post/1725601/


All Articles