Default argument

Default argument

In computer programming, a default argument is an argument to a function that a programmer is not required to specify. A default value is specified when the function is declared and the default value is automatically passed to the function when it is called. Default argument is a part of a function declaration and it tells compiler to pass the value for an argument if programmer deliberately misses an argument while calling the function. In the common case that many arguments are almost always the same. This saves programmer's time and effort required to remember and specify all arguments. Default arguments are useful in situations where some arguments always have the same value. For instance, bank interest may remain same for all customers for a particular period of deposit. It also provides greater flexibility to programmers.

Contents

Variation among languages

Most of the Object Oriented Programming (list of Object Oriented Programming languages) languages allow to use default arguments. Variation in the syntax is seen in these languages. Languages like C++, Python and Java etc. are popular in the world of computer programming.

C++

C++ allows to specify default arguments. In C++ the function assigns a default value to the 'parameter' which does not have a matching argument in function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses though the programmer assigns less value of the arguments than declared at the time of function call and compiler alerts the program for possible default values.

Usage with syntax

Here is an example of a function prototype (i.e., function declaration) with a default argument:

float calcInterest(float principal, int period, float rate = 0.05)

Here rate is declared as a default parameter, with default value 0.05.

The function calcInterest is written with only two arguments but the third will get passed automatically. The compiler memorizes the default argument so it knows it can still make the function call if it substitutes this third argument which is what user have told it to do by making it a default.

value = calcInterest(123.45, 6)

Here principal gets the value 123.45, period gets the value 6 and rate gets the (default) value 0.05.

calcInterest may also be called with three arguments overriding the default rate:

value = calcInterest(123.45, 6, 0.07)

Caution

One important point to note is that only trailing arguments can have default values and therefore while declaring the function defaults must be added from right to left.

int mul (int i, int j = 5, int k = 10); // Right declaration.
int mul (int i = 5, int j); // wrong declaration.

Illustration with program

#include <iostream>
using std::cout;
 
float value(float p, int n, float r = 0.15);
void printline(char ch = '*', int len = 10);
 
int main()
{
        float amount;
        printline();
        amount = value(5000.00, 5);
        cout << "\n Final value = " << amount << "\n";
        printline('=');
        return 0;
}
float value(float p, int n, float r)
{
        int year = 1;
        float sum = p;
        while(year <= n)
        {
                sum = sum*(1+r);
                year = year+1;
        }
        return (sum);
}
void printline(char ch, int len)
{
        for(int i = 1; i <= len; i++)
        {
                cout << ch;
        }
 
        cout << "\n;
}

Output of the above program is-

****************************************
Final Value = 10056.8
========================================

Description of the program

Working of function with Default argument

In the above program while declaring the function value, r is initialized to 0.15 while p and n have not been initialized. So, while calling the function, values of p and n are provided and the value of r is not provided, but the default value of r i.e. 0.15 was passed automatically. If the values of p and n would have been initialized in the function value, then these values would have been override by the values provided while calling the function, the similar concept is used while calling the printline function. Here the char '*' is override by '='. The figure shown here illustrates the working of default arguments. In function declaration only the value of z has been declared and the values of y and z are passed during the function call and as per the rule all 3 values are passed to the function definition.

Python

In python, a function can be called with following 4 arguments.

1. Keyword arguments

2. Required arguments

3. Variable length arguments

4. Default arguments

Like c, python also allows to specify default arguments and to pass them automatically to the function which has been called. More than one default values should be specified at the time of declaration. This will create a new function that can be called with fewer arguments than it is defined to allow.

Illustration

The following program can be called in several ways to pass the default arguments.

def que_ok(prompt, again=4, complaint='state yes or no'):
        while true:
                ok = raw_input(prompt)
                if ok in ('yes'):
                        return true
                if ok in ('no'):
                        return false
                again = again - 1
                if again < 0:
                        print complaint

The default values are evaluated at the function definition in the defining scope....so that e.g.

          i = 7
          def f(arg = i): print arg
          i = 8
          f()

The working of the above function is very much similar as it is in c++ hence the above code will print 7.

To illustrate default arguments much clearly in python language refer a program in python language for default arguments.

Java

Java does not support default arguments, but a similar result can be achieved with method overloading. This involves declaring multiple methods with the same name and a different number of arguments. Often the implementation of the version(s) with fewer arguments is delegated to the version with more:

float calcInterest(float principal, int period, float rate) { /* main implementation here */ }
float calcInterest(float principal, int period) { return calcInterest(principal, period, 0.05) }

The default arguments in c++ can be converted into java. This is illustrated in the following program.

Area program for c++

int area(int a, int w = 0)
{
       if (w == 0)
               return l * l;
       else
               return l * w;
}
int main()
{
        cout<<"area of rectangle "<<endl;
        cout<<area(3 , 4)<<endl;
        cout<<"area of square "<<endl;
        cout<<area(3)<<endl;
        return 0;
}

Now to convert the above code into java without using default arguments,simply create overloaded methods that handles each case. Using this approach the above code can be written in java as follows-

static int area(int a, int b) //compute area for rectangle
{
        if (w == 0)
               return l * l;
        else 
               return l *w;
}
static int area(int a) //overloaded area for square
{
        return l * l;
}
public static void main()
{
        System.out.println("Area of rectangle " + area(3, 4));
        System.out.println("Area of square " + area(3));
}

References

  1. http://people.cs.vt.edu/~kafura/cs2704/default.html
  2. Object Oriented Programming Language with C++. Author- E. Balagurusamy.
  3. Default Arguments in C++ Functions

External links

  1. http://oopweb.com/CPP/Documents/ThinkingInCpp1/Volume/Chapter07.html
  2. http://stackoverflow.com/questions/5748264/default-arguments-in-c
  3. examples in c++ for default arguments
  4. www.javasamples.com
  5. publib.boulder.ibm.com
  6. Default arguments for templates parameter in C++
  7. Alternatives in java

See also


Wikimedia Foundation. 2010.

Игры ⚽ Нужно решить контрольную?

Look at other dictionaries:

  • Argument (disambiguation) — In general parlance, an argument is a discussion involving conflicting points of view. General types of argument * Argument, a demonstration of a proof, or using logical reasoning for persuasion * Argument form, the logical structure of an… …   Wikipedia

  • Default constructor — In computer programming languages the term “default constructor” refers to a constructor that is automatically generated in the absence of explicit constructors (and perhaps under other circumstances); this automatically provided constructor is… …   Wikipedia

  • Command-line argument — In computer command line interfaces, a command line argument is an argument sent to a program being called. In general, a program can take any number of command line arguments, which may be necessary for the program to run, or may even be ignored …   Wikipedia

  • Doomsday argument — World population from 10,000 BC to AD 2000 The Doomsday argument (DA) is a probabilistic argument that claims to predict the number of future members of the human species given only an estimate of the total number of humans born so far. Simply… …   Wikipedia

  • Procedural default — is a concept in American Federal Courts law that requires a state prisoner seeking a writ of Habeas Corpus in federal court to have present [ed] his federal law argument to the state courts [on direct review] in compliance with state procedural… …   Wikipedia

  • Credit default swap — Produits dérivés financiers Produits fermes Forwards (Contrat de gré à gré) Futures (Contrat à terme) Swaps (Échange financier) Produits optionnels Options et Warrants Credit default swap (couvertures de défaillance) …   Wikipédia en Français

  • Credit Default Swap — Les dérivés sur événement de crédit[1] ou en anglais Credit Default Swaps (CDS) sont des contrats financiers de protection, entre acheteurs et vendeurs. L acheteur de protection verse une prime[2] ex ante annuelle calculée sur le montant… …   Wikipédia en Français

  • command-line argument —    A parameter that alters the default mode of a command. In many operating systems, a commandline argument is one or more letters or numbers preceded by the / (slash) character. In Unix, a command line argument may be called an option or a flag… …   Dictionary of networking

  • Parameter (computer science) — In computer programming, a parameter is a variable which takes on the meaning of a corresponding argument passed in a call to a subroutine. In the most common case, call by value, a parameter acts within the subroutine as a local (isolated) copy… …   Wikipedia

  • Stdarg.h — is a header in the C standard library of the C programming language that allows functions to accept an indefinite number of arguments. C++ provides this functionality in the header ; the C header, though permitted, is deprecated in C++.The… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”