Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

default parameters without name in c ++

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...

like image 780
nupadhyaya Avatar asked Jan 27 '13 06:01

nupadhyaya


People also ask

Can you have default parameters in C?

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.

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

Can you have optional parameters in C?

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 ).

What are the parameters that are default?

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.


2 Answers

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);
like image 105
billz Avatar answered Sep 28 '22 06:09

billz


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

like image 31
B. Angelucci Avatar answered Sep 28 '22 05:09

B. Angelucci