Default Value

A DefaultValue in programming languages is typically the value of a FunctionParameter?, ClassMember?, GlobalVariable or LocalVariable? when no other value was explicitly provided. For example, in JavaLanguage, every class member of type "int" takes on the default value of 0, and every class member of class type defaults to null.

Default values aren't the only way to handle this situation:

The typical behavior of C++ implementations is to emit a CompileTime warning when FlowAnalysis? detected that an uninitialized variable is read from, and just use uninitialized memory at runtime.

The following code in CeePlusPlus defines a default value for a function parameter. It will be used whenever a call to this function omits the last parameter:

 int add_mod(int a, int b, int modulo = 10) {
 return (a + b) % modulo;
 }
In functions like Java and C# that do not allow default parameters, this behavior can be emulated through the use of FunctionOverloading?:
 static int add_mod(int a, int b, int modulo) {
 return (a + b) % modulo;
 }
 static int add_mod(int a, int b) {
 return (a + b) % 10;
 }
or
 static int add_mod(int a, int b, int modulo) {
 return (a + b) % modulo;
 }
 static int add_mod(int a, int b) {
 return add_mod(a, b, 10);
 }
or
 static final int modulo_base = 10;
 static int add_mod(int a, int b, int modulo) {
 return (a + b) % modulo;
 }
 static int add_mod(int a, int b) {
 return add_mod(a, b, modulo_base);
 }
This is sometimes useful in C++ as well, because this approach is more flexible than providing default values. The disadvantage is its verbosity, especially if multiple default-valued parameters are to be emulated.


EditText of this page (last edited May 14, 2006) or FindPage with title or text search