Default Argument Initializers

Local variable may not be used as a default argument. Excepting that restriction, a default argument can be any expression that has a type that is convertible to the type of the parameter:

// the declarations of wd, def, and ht must appear outside a function
sz wd = 80;
char def = ' ';
sz ht();                  // a function declaration
string screen(sz = ht(), sz = wd, char = def);
string window = screen(); // calls screen(ht(), 80, ' ')

Names used as default arguments are resolved in the scope of the function declaration. The value that those names represent is evaluated at the time of the call:

void f2()
{
    def = '*';          // changes the value fo a default argument
    sz = wd = 100;      // hides the outer definition of wd but does not change the default
    window = screen();  // calls screen(ht(), 80, '*')
}

Inside f2, we changed the value of def. The call to screen passes this updated value. Our function also declared a local variable that hides the outer wd. However, the local named wd is unrelated to the default argument passed to screen.

发表评论

电子邮件地址不会被公开。 必填项已用*标注

20 + 16 =

− 1 = 3