Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put default parameter value in C++? [duplicate]

What's the place for the default parameter value? Just in function definition, or declaration, or both places?

like image 783
Thomson Avatar asked Feb 14 '11 06:02

Thomson


People also ask

Where can the default parameter be placed by the?

Where can the default parameter be placed by the user? Explanation : None.

Where should be the default value of parameter be specified?

We can provide a default value to a particular argument in the middle of an argument list.

How do you set a parameter to default value?

In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined .

Can you set default arguments in C?

Yes. :-) But not in a way you would expect. Unfortunately, C doesn't allow you to overload methods so you'd end up with two different functions. Still, by calling f2, you'd actually be calling f1 with a default value.


2 Answers

Default parameter values must appear on the declaration, since that is the only thing that the caller sees.

EDIT: As others point out, you can have the argument on the definition, but I would advise writing all code as if that wasn't true.

like image 187
Marcelo Cantos Avatar answered Sep 22 '22 16:09

Marcelo Cantos


You can do either, but never both. Usually you do it at function declaration and then all callers can use that default value. However you can do that at function definition instead and then only those who see the definition will be able to use the default value.

like image 25
sharptooth Avatar answered Sep 19 '22 16:09

sharptooth