Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the result of a function call be used as a default parameter value?

Is there a good method for writing C / C++ function headers with default parameters that are function calls?

I have some header with the function:

int foo(int x, int y = 0);

I am working in a large code base where many functions call this function and depend on this default value. This default value now needs to change to something dynamic and I am looking for a way to do:

int foo(int x, int y = bar());

Where bar() is some function that generates the default value based on some system parameters. Alternatively this function prototype would look like:

int foo(int x, int y = baz.bar());

Where baz is a function belonging to an object that has not been instantiated within the header file.

like image 578
TJ Seabrooks Avatar asked Oct 14 '08 20:10

TJ Seabrooks


People also ask

Is it possible to give a default value to a function parameter?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

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

All the parameters of a function can be default parameters.

What is the default value of parameter?

The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.

Which parameter Cannot have a default value?

An IN OUT parameter cannot have a default value. An IN OUT actual parameter or argument must be a variable.


2 Answers

Go figure! It does work. Default arguments in C++ functions

like image 182
Dima Avatar answered Sep 22 '22 03:09

Dima


I would use two overloaded functions:

int foo(int x, int y);

int foo(int x){return foo(x,bar);}

If you allow the forwarding function to be inlined, then the performance penalty is likely to small to zero. If you keep the body of it out of line in a non-header file there may be a performance cost (likely to be small), but much more flexibility in implementation and reduced coupling.

like image 40
Tim Sharrock Avatar answered Sep 22 '22 03:09

Tim Sharrock