Consider the functions:
void foo(int a = 3)//named default parameter
void foo1(int = 3)//unnamed default parameter
I understand the need of the first function.(The value of "a" is 3 and it can be used in the program). But the 2nd function(which is not an error) has 3 initialized to nothing. How exactly do i use this value , if i can use this value...
There are no default parameters in C. One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed.
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.
Optional arguments are generally not allowed in C (but they exist in C++ and in Ocaml, etc...). The only exception is variadic functions (like printf ).
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.
In function declaration/definition, a parameter may have or have not a name, this also applies to a parameter with default value.
But to use a parameter inside a function, a name must be provided.
Normally when declare a function with default parameter
// Unnamed default parameter.
void foo1(int = 3);
In function definition
void foo1(int a)
{
std::cout << a << std::endl;
}
Then you can call
foo1(); // the same as call foo1(3)
foo1(2);
I've found the 2nd declaration very useful when declaring an empty virtual method of a base class
virtual void doSomething(bool = false) {};
I don't want to make it pure virtual since in many derived classes I don't want to re-implement it, so I leave it empty in the base class.
But I need the default value false
when implementing this method in some other derived classes.
virtual void doSomething(bool en = false) {};
This is not wrong but the compiler gives the unused parameter warning
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With