Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ default function parameter

Tags:

c++

I want to achieve this:

- second parameter by default set to first argument

Something like:

int foo (int a, int b = a);

But how to do that?

Thanks a lot!

like image 450
user180574 Avatar asked Oct 11 '12 19:10

user180574


People also ask

Can C functions have default parameters?

Generally no, but in gcc You may make the last parameter of funcA() optional with a macro.

What is default function 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.

What are C functions by default?

The Main Function in C Programming By default, the return type of the main function is int. There can be two types of main() functions: with and without parameters.

How C function parameters arguments are passed by default?

Default Arguments in C++ A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.


2 Answers

This is forbidden by:

8.3.6 Default arguments [dcl.fct.default]

9) Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in default argument expressions, even if they are not evaluated. Parameters of a function declared before a default argument expression are in scope and can hide namespace and class member names. [ Example:

int a;

int f(int a , int b = a); / / error: parameter a

/ / used as default argument

typedef int I;

int g( float I , int b = I (2)); / / error: parameter I found

int h(int a , int b = sizeof (a )); / / error, parameter a used

/ / in default argument

—end example ]

An alternative is overloading:

int foo(int a, int b);

int foo(int a)
{
   return foo(a,a);
}
like image 89
Luchian Grigore Avatar answered Oct 05 '22 22:10

Luchian Grigore


The reason this is disallowed has already been addressed, but another solution along the lines of @Vyktor's is to use boost::optional instead of magic numbers (This has pros and cons compared to creating an overload):

int foo(int a, boost::optional<int> b = boost::none)
{
    if(!b) b = a;
}
like image 37
Mark B Avatar answered Oct 06 '22 00:10

Mark B