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
AI in Programming
Artificial Intelligence (AI) has revolutionized numerous fields, and programming is no exception. From automating repetitive tasks to enhancing decision-making processes, AI is reshaping how software is developed, maintained, and utilized across various industries. This article explores the intersec
7 min read
Assignment Operators in Programming
Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improvin
7 min read
Arithmetic Operators in Programming
Arithmetic operators are fundamental components of programming languages that allow developers to perform mathematical operations on numerical data types. These operators enable manipulation of numeric values, making them essential for various computational tasks. Table of Content What are Arithmeti
7 min read
Learn Programming For Free
Programming, also known as coding, is the process of creating a set of instructions that tell a computer how to perform a specific task. These instructions, called programs, are written in a language that the computer can understand and execute. Welcome to our journey into the world of programming!
6 min read
Introduction to GUI Programming in C++
In C++, Graphical User Interface (GUI) programming is important in modern application development where users have nice graphics for them to work with. Although C++ is commonly linked with system programming and game writing, it can be an excellent alternative to GUI writing. In this article, we wil
5 min read
What is a Code in Programming?
In programming, "code" refers to a set of instructions or commands written in a programming language that a computer can understand and execute. In this article, we will learn about the basics of Code, types of Codes and difference between Code, Program, Script, etc. Table of Content What is Code?Co
10 min read
What are Operators in Programming?
Operators in programming are essential symbols that perform operations on variables and values, enabling tasks like arithmetic calculations, logical comparisons, and bitwise manipulations. In this article, we will learn about the basics of operators and their types. Table of Content What are Operato
15+ min read
Binary Operators in Programming
Binary Operators are essential tools in programming that perform operations on pairs of data, enabling tasks like calculations, comparisons, logical operations, and bitwise manipulations. They are fundamental for processing and manipulating data efficiently in computer programs. Table of Content Wha
14 min read
Most Famous Online IDE for Programming
Integrated Development Environment (IDE) provides crucial tools for software development. IDE provides developers with tools like code editor, compiler, interpreter, debugger, code library, and testing tools that help developers in writing, compiling, debugging, and testing the code. Without IDE dev
5 min read
Programming Construction in COBOL
COBOL is a compiled, imperative, procedural programming language designed for business use. It can handle very large numbers and strings. COBOL is still in use today because it's robust, with an established code base supporting sprawling enterprise-wide programs. Learning to program in COBOL will se
5 min read