47
void func ( string word = "hello", int b ) {

  // some jobs

}

in another function

 //calling 
 func ( "", 10 ) ;

When I have compiled it, compiler emits error ;

default argument missing for parameter 

How can I fix it without changing anything, of course, such as not making "int b = 0" ? Moreover, I want use that function like func ( 10 ) or func ( "hi" ) ? Is my compiler not do its job, properly ?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 2
    Are you trying to do this : [Default argument in the middle of parameter list?](http://stackoverflow.com/questions/5637679/default-argument-in-the-middle-of-parameter-list) – Nawaz Apr 21 '11 at 06:54

5 Answers5

88

You can't have non-default parameters after your default parameters begin. Put another way, how would you specify a value for b leaving word to the default of "hello" ?

cnicutar
  • 178,505
  • 25
  • 365
  • 392
35

The arguments with a default value have to come in the end of the argument list.

So just change your function declaration to

void func(int b, string word = "hello")
Chris
  • 2,030
  • 1
  • 16
  • 22
15

Parameters with default values have to come at the end of the list because, when calling the function, you can leave arguments off the end, but can't miss them out in the middle.

Since your arguments have different types, you can get the same effect using an overload:

void func ( string word, int b ) {

  // some jobs

}

void func ( int b ) { func("hello", b); }
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
9

The error message is proper. If the default argument is assigned to a given parameter then all subsequent parameters should have a default argument. You can fix it in 2 ways;

(1) change the order of the argument:

void func (int b, string word = "hello");

(2) Assign a default value to b:

void func (string word = "hello", int b = 0);
iammilind
  • 68,093
  • 33
  • 169
  • 336
5

You cannot fix it without changing anything!

To fix it, you can use overloading:

void func ( string word, int b ) {
  // some jobs
}

void func ( string word ) {
    func( word, 999 );
}

void func ( int b ) {
    func( "hello", b );
}
anatolyg
  • 26,506
  • 9
  • 60
  • 134