Default Argument in Programming
Last Updated :
18 Apr, 2024
Default arguments are one of the powerful features in programming that allows developers to specify a default value for one or more parameters in a function and provides flexibility as it enables functions to be called with different numbers of arguments. When calling a function, the programmer can omit some of the arguments for parameters that have default values, and the function will use those default values instead which makes functions more versatile and user-friendly. Languages like C++, Python, etc. allow the programmer to specify default arguments that always have a value, even if one is not specified when calling the function.
What are Default Arguments?
Default Arguments are parameters in a function or method that have a default value assigned to them. These default values are used when a value for that parameter is not provided during the function call.
Here are some key points about default arguments:
- Automatic Assignment: If the function is called without providing a value for the argument, the default value is automatically assigned.
- Overriding: If a value is passed for the argument, the default value is overridden.
- Order of Arguments: Typically, default arguments are placed after non-default arguments in the function definition.
- Flexibility: Default arguments provide flexibility, allowing a function to be called with varying numbers of arguments.
- Use Cases: Default arguments are particularly useful when a function has many parameters, and only a few of them need to be specified most of the time
Syntax of Default Argument:
Depending on the programming language, different syntaxes are used to express default arguments. Default arguments are usually declared in the signature of a function by setting the parameter's value.
C++
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
return (x + y + z + w);
}
Python3
def default_Aargument(default_arg = 'This is defaults argument'):
print(default_arg)
JavaScript
function fnName(param1 = defaultValue1, /* …, */ paramN = defaultValueN) {
// …
}
Default Argument in C++:
Here is the implementation of the default argument in C++:
C++
// CPP Program to demonstrate Default Arguments
#include <iostream>
using namespace std;
// A function with default arguments,
// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
return (x + y + z + w);
}
// Driver Code
int main()
{
// Statement 1
cout << sum(10, 15) << endl;
// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Default Arguments and Function Overloading in C++:
Function overloading is a common practice in languages such as C++. There are some rules and restrictions when using preset parameters in function overloading:
- Consistency: Overloaded functions must have a clear and specific purpose. Default parameters should not cause ambiguity in the calls.
- Parameter positioning: To avoid confusion/misunderstanding during function calls, default arguments in a function declaration must come after all non-default parameters.
- Ambiguity in function calls: Sometimes combining overload with presets can be confusing. For example, if there are many overloaded functions with preset parameters, the compiler will have difficulty deciding which overloaded function to call.
In C++, consider the following overloaded functions:
C++
#include <iostream>
using namespace std;
void printMessage(int count, string message = "Hello");
void printMessage(int count, bool includeTimestamp = false);
int main() { printMessage(5); }
The parameter lists for both functions are similar and they share the same name "printMessage". If you call printMessage(5) with just one integer argument, there might be ambiguity about which function to use.
You must make sure that the parameter types and order of each overloaded function are unique in order to resolve ambiguity.
Default Argument in Python:
Default arguments in Python can be used with two types of arguments:
- With Keyword Arguments
- Without Keyword Arguments
Default Argument with Keyword Argument:
Here is the implementation of default argument with keyword:
Python3
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard, 'Standard')
# 1 keyword argument
student(firstname ='John')
# 2 keyword arguments
student(firstname ='John', standard ='Seventh')
# 2 keyword arguments
student(lastname ='Gates', firstname ='John')
OutputJohn Mark studies in Fifth Standard
John Mark studies in Seventh Standard
John Gates studies in Fifth Standard
Default Argument without Keyword Argument:
Here is the implementation of default argument without keyword:
Python3
def student(firstname, lastname ='Mark', standard ='Fifth'):
print(firstname, lastname, 'studies in', standard, 'Standard')
# 1 positional argument
student('John')
# 3 positional arguments
student('John', 'Gates', 'Seventh')
# 2 positional arguments
student('John', 'Gates')
student('John', 'Seventh')
OutputJohn Mark studies in Fifth Standard
John Gates studies in Seventh Standard
John Gates studies in Fifth Standard
John Seventh studies in Fifth Standard
Default Argument in Javascript:
Here is the implementation of the default argument in javascript:
JavaScript
function greet(name) {
// If name is not provided, use 'World' as the default
name = typeof name !== 'undefined' ? name : 'World';
console.log("Hello, " + name + "!");
}
// Test cases
greet(); // Output: Hello, World!
greet("John"); // Output: Hello, John!
OutputHello, World!
Hello, John!
Default Argument in Java:
In Java, there's no direct support for default arguments in methods as in some other languages like Python or C++. However, you can achieve similar functionality through method overloading or using the Builder pattern.
Method Overloading: You can define multiple versions of a method with different parameter lists. One version of the method can have fewer parameters and provide default values for those parameters.
Java
public class Example {
public void greet() {
greet("World"); // calling the version of greet method with default argument
}
public void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}
In this example, greet()
method without parameters acts as an entry point and calls the greet(String name)
method with the default argument "
World
"
.
Builder Pattern: The Builder pattern is useful when you have a complex object with many optional parameters. You can use it to set default values for those parameters.
Java
public class Person {
private String name;
// Builder pattern to set default values
public static class Builder {
private String name = "World";
public Builder() {}
public Builder name(String name) {
this.name = name;
return this;
}
public Person build() {
return new Person(this);
}
}
private Person(Builder builder) {
this.name = builder.name;
}
public void greet() {
System.out.println("Hello, " + name + "!");
}
}
In this example, the Builder
class sets the default value for name
as "
World
"
. When Person
object is created without specifying the name, it defaults to "
World
"
.
Advantages of Default Argument:
- Flexibility: Default values can be substituted for some arguments, which makes the function calls more flexible.
- Readability: Efficient use of default parameters helps to make the code clearer and easily comprehensible.
- Maintainability: This implies that if you change the default value, this will have an effect on the behaviour of your program without changing much at all.
- Reduced Code Duplication: Default arguments could potentially cut down on redundant code by letting a single function handle many cases with different parameter values thus saving multiple comparable functions.
Disadvantages of Default Argument:
- Code ambiguity: If default parameters are used excessively and are not properly managed, this might result in unclear code and unexpected behaviour.
- Complexity: Default arguments and overloaded functions can often cause confusion and complexity, particularly when function overloading is involved.
- Increased Execution time: Because the compiler must substitute the missing arguments for their default values in the function call, it lengthens the execution time.
- Problems with debugging: Debugging code might be more challenging due to the fact that it's not always possible to see the default arguments in the call stack, which might make it challenging to identify the reason of an error.
Conclusion:
Programming languages provides a very useful and adaptable feature referred to as default arguments that, when used properly, can enhance the clarity, maintainability, and flexibility of programs. Understanding the benefits, how to use them properly, and any potential risks are important for writing clear and efficient code. Developers can successfully add default arguments to their apps if they adhere to best practices and take into account the unique features of the language.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem