Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must default function parameters be constant in C++?

Tags:

c++

void some_func(int param = get_default_param_value());
like image 740
Sergey Skoblikov Avatar asked Dec 02 '08 18:12

Sergey Skoblikov


People also ask

Do default parameters have to be last?

Rule Details. This rule enforces default parameters to be the last of parameters.

CAN default arguments be constants?

Default arguments are different from constant arguments as constant arguments can't be changed whereas default arguments can be overwritten if required. Default arguments are overwritten when the calling function provides values for them.

Can all the parameters of a function can be default parameters?

C. All the parameters of a function can be default parameters.

Should function parameters be const?

Always use const on function parameters passed by reference or pointer when their contents (what they point to) are intended NOT to be changed. This way, it becomes obvious when a variable passed by reference or pointer IS expected to be changed, because it will lack const .


2 Answers

Default parameter can be a subset of the full set of expressions. It must be bound at compile time and at the place of declaration of the default parameter. This means that it can be a function call or a static method call, and it can take any number of arguments as far as they are constants and/or global variables or static class variables, but not member attributes.

The fact that it is bound at compile time and in the place where the function is declared also means that if it makes use of a variable, that variable will be used even if a different variable shadows the original at the place of the function call.

// Code 1: Valid and invalid default parameters
int global = 0;
int free_function( int x );

class Test
{
public:
   static int static_member_function();
   int member_function();

   // Valid default parameters
   void valid1( int x = free_function( 5 ) );
   void valid2( int x = free_function( global ) );
   void valid3( int x = free_function( static_int ) );
   void valid4( int x = static_member_function() );

   // Invalid default parameters
   void invalid1( int x = free_function( member_attribute ) ); 
   void invalid2( int x = member_function() );
private:
   int member_attribute;
   static int static_int;
};

int Test::static_int = 0;

// Code 2: Variable scope
int x = 5;
void f( int a );
void g( int a = f( x ) ); // x is bound to the previously defined x
void h()
{
   int x = 10; // shadows ::x
   g(); // g( 5 ) is called: even if local x values 10, global x is 5.
}
like image 92
David Rodríguez - dribeas Avatar answered Oct 09 '22 08:10

David Rodríguez - dribeas


They don't have to be! A default parameter can be any expression within certain limitations. It is evaluated every time the function is called.

like image 42
Sergey Skoblikov Avatar answered Oct 09 '22 07:10

Sergey Skoblikov