Default Argument Expressions

The expressions used for default arguments are often constant expressions, but this is not a requirement. The expression can combine functions that are visible in the current scope, constant expressions, and global variables. The expression cannot contain local variables or non-static class-member variables. The following code illustrates this:

BOOL CreateVScrollBar( HWND hWnd, short nWidth =
GetSystemMetrics( SM_CXVSCROLL ) );

The preceding declaration specifies a function that creates a vertical scroll bar of a given width for a window. If no width argument is supplied, the Windows API function, GetSystemMetrics, is called to find the default width for a scroll bar.

The default expression is evaluated after the function call, but the evaluation is completed before the function call actually takes place.

Because formal arguments to a function are in function scope, and because the evaluation of default arguments takes place prior to entry to this scope, you cannot use formal arguments, or local variables in default argument expressions.

Note that any formal argument declared before a default argument expression can hide a global name in the function scope, which can cause errors. The following code is illegal:

const int Categories = 9;
void EnumCategories( char *Categories[], int n = Categories );

In the preceding code, the global name Categories is hidden at function scope, making the default argument expression invalid.

See Also

Reference

Default Arguments